View RSS Feed

My Java Tips

Using Interfaces

Rate this Entry
by , 11-10-2011 at 05:32 PM (883 Views)
Interfaces are used to define a contract for the classes. It has its own importance when it comes to defining standards.


Consider the following example:

Cars have some standard and their basic operations are the same. Each car should have operations like startCar, moveCar, stopCar etc. Toyota, Mazda and Honda are cars and each has its own way of starting, moving and stoping. So each has to have its own startCar, moveCar and stopCar method.

How to enforce each car class to have these methods according to agreed standard (signature)? Interfaces are those contracts, that have to be used in such situations.

Some important points about interfaces are:
Interfaces can only have constants and method signature. Method body is not allowed. Interfaces can only be implement by other classes or extended my other interfaces. A class implementing an interface, has to override all methods defined in the interface.

Lets see how to define an interface:

Java Code:
public interface Car {
public void startCar();
public void stopCar();
public void moveCar();
}
Honda class implements Car interface and has to provide method definition of all the methods signatures defined in the interface.

Java Code:
public class Honda implements Car{

	public static void main(String[] args){
		//...
	}

	public void startCar()
	{
	// ...
	}

	public void stopCar()
	{
	// ...
	}

	public void moveCar()
	{
	// ...
	}

}
If you miss a method whose signature exist in the interface your class is implementing then its a syntax error and compiler will show an error. For instance, if you don't define method moveCar() in Honda class, you will get this error message:

The type Honda must implement the inherited abstract method Car.moveCar()

Submit "Using Interfaces" to Facebook Submit "Using Interfaces" to Digg Submit "Using Interfaces" to del.icio.us Submit "Using Interfaces" to StumbleUpon Submit "Using Interfaces" to Google

Comments