What is an interface? Explain with an example using java.
A class that implements an interface is compelled to implement all the methods that have been declared in the interface.
For a class to successfully compile, it should have implemented all the methods in the interface. This way, the interface makes the behavior of the class formal by defining its behaviour.
Syntax: interface INTERFACE_NAME
{
return_type method1_name();
return_type method2_name();
}
class CLASS_NAME implements INTERFACE_NAME
{
return_type method1_name()
{
//implementation method1
//implementation method2
}
}
Advantages and disadvantages of interfaces.
Advantages - Interfaces are mainly used to provide polymorphic behavior.
- Interfaces function to break up the complex designs and clear the dependencies between objects.
Disadvantages- Java interfaces are slower and more limited than other ones.
- Interface should be used multiple number of times else there is hardly any use of having them.