Interface
Interface is a an abstract type that can be used only after implementation by the class that implements the interface. It is important to know that interface does not define any methods, it just tell the outside world that a class that implements this interface will have all the methods defined in the interface. Interface may contain only method signature as as I said before and constant declaration which means the variables declared are both static and final. The mehods defined in the interace are public and abstract in nature. There cannot be a method of type final.Example
interface Car{
void changeGear(int newValue);
void accelerate(int accelerateValue);
void decelerate(int decelerateValue);
}
Class
MarutiCar), and you'd use the implements keyword in the class declaration.Example
class MarutiCar implements Car{
//class variables
// remainder of this class
// implementation of the interface methods
}
Comprehensive Example
class MarutiCar implements Car{String ACModel;
public void changeGear(int newValue){
// change gear operation
}
public void accelerate(int accelerateValue){
// accelerate operation
}
void decelerate(int decelerateValue)
// decelerate operation
}
public static void main(String args[]) {
// Object creation
MarutiCar myCar = new MarutiCar();
// Call a method
myCar.ChangeGear(2);
}
}
Unlike interface the class variables need not be final and static. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Interface also helps in multiple inheritance which cannot be done with normal classes. A class can implement two interfaces but cannot inherit two classes in java.