Interface is a template or blue print of the class. This defines some set of instructions that classes which uses the interface should be implemented.
The interface is used to achieve a complete 100% abstraction. Interfaces contain abstract methods, variables are in the interface are static, public & final by default.
Interface is also used to achieve multiple inheritance in java.
Interface is used to achieve complete 100% abstraction. so there will be no method body for the abstract methods, to access the abstract method ,we should create a class for the interface.
All methods inside the interface are implicitly public and all fields are implicitly public static final
relationship between classes and interfaces
Class can extend to another class
to use an interface, class implements an interface, because we cannot create objects of interfaces
interfaces can extend to another interface
Syntax for class implements an interface
To use interface, we should create a class using implements keyword to use interface with the class
Example for Using Interface
In the above example interface is an animal, so every class can be implemented animal interface, the animal interface has a sound( ) method, so in the dog class, body of the sound( ) method can be declared. we are creating an object to the dog class, now we can call the sound( ) method
extends Keyword in Interface
As we discussed above, one interface can extend to a new interface, just like a class can extend to the new class. The extends keyword is used for extending interfaces
Example for extending interface
In the above program interface, A is used to extend Interface B, each interface has its own method. we created a class called demo using implements keyword and boy of the two methods methodA( ) and methodB( ) is created in the implemented class. Object is created and two methods are called
How Multiple inheritances in Java is possible by an interface
By using class multiple inheritance is not possible because of ambiguity, but in the interfaces ,methods are abstract,so you can declare the method with the same name ,but can’t write the method body inside the interface, check out the example below
Example Multiple inheritances in Java using interface