Thursday, January 15, 2009

Interfaces in JAVA (Java Fundamentals)

An interface is similar to Abstract classes but the only difference here is an interface cannot have any code implementation within it's body. Interfaces serves as a prototype for the whole project, so that all the clasess implementing an interface would override the methods in it.

Here are the features and rules of an Interface:


  1. Interface can only be declared with public or default access modifiers
  2. Any method declared within an Interface is "public abstract"
  3. Any method declared within an interface should not have code implementations
  4. Any variables declared within an Interface is "public static final", in other words all of them will be constant values.
  5. A sub-class that does not override an Interface method/s should be declared abstract.
  6. An Interface can implement several interfaces.
  7. "extends" keyword is used for an interface to implement another interface

Let's take an example to figure out how actually an interface works. Let's expand the previous example "The Car Scenario". Now what are the common features of a Vehicle? Every modern Vehicle will have it's own engine, color and maximum speed (kmh). This feature will vary in accordance to the type of Vehicle. An economic car could have 4 seats, metalic or non-metalic color, and etc. Have a look at this code to see how actually interfaces are implemented for the Economic car.


interface Vehicle {
int engine() ;
int speed() ;
}

interface Color
{
String colorType() ;
boolean isMetalic() ;
}

interface Car extends Vehicle, Color
{
int numSeats() ;
}

public class EconomicCar implements Car
{
public int engine()
{
int cylinder = 6 ;
return cylinder ;
}

public int speed()
{
int maxSpeed = 200 ;
return maxSpeed ;
}

public String colorType()
{
String color = "black" ;
return color ;
}

public boolean isMetalic()
{
boolean metalic = true ;
return metalic ;
}

public int numSeats()
{
int seats = 4 ;
return seats ;
}
}


Every car will have it's own engine, color and max speed so, the Car interface implements both Color and Vehicle interface. The Car interface has it's own abstract method called numSeats beacuse number of seats vary for different type of cars. The sub-class of the whole hirearchy is EconomicCar, and this sub-class has to override all the abstract methods of it's super-classes.





Author: Thiagu

No comments:

Post a Comment