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:
- Interface can only be declared with public or default access modifiers
- Any method declared within an Interface is "public abstract"
- Any method declared within an interface should not have code implementations
- Any variables declared within an Interface is "public static final", in other words all of them will be constant values.
- A sub-class that does not override an Interface method/s should be declared abstract.
- An Interface can implement several interfaces.
- "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