Interface
in java is like a contract with the implementing class
. When you implement an interface you have to make sure that either you implement all the methods in the interface
or make your class abstract
. Lets take a real like analogy.
You are creating a Car. Now as you know there can be a number of cars out there i.e. Mercedes, BMW, Audi and so on. You want to make sure that each Car should contain changeGear()
, hasWheels()
, hasDoors()
methods in them, so how would you force this criteria on all possible cars. Simply create an interface
named Car
that has all these methods in it like
public interface Car{
boolean changeGear();
boolean hasWheels();
boolean hasDoors();
}
Now every class
that implements this interface
has to implement all these methods. So, in future if you create a Ferrari
class implementing Car interface it has to abide by this contract.
Edit: A thing to note here is that all the classes that implement the interface
are not restricted to use only the methods from the interface. It is just like the implementing class
has to make sure that it at least implements the methods from interface
. Like in our example Ferrari
class can very well implement the isSportCar()
method which is only contained in Ferrari
class.