Interfaces in Java
An interface in Java is a blueprint of a class, containing a collection of abstract methods (methods without a body) and constant variables. It defines a contract that classes must follow when they implement the interface.
Declaring an Interface
We use the "interface" keyword to declare an interface;
Any class with interface "Shape"must have implementation of calculatePArea() and calculatePerimeter() methods.
Implementing an Interface
We use "implements" keyword to implement interface.
Multiple Inheritance and Interfaces
Java supports multiple inheritance through interfaces. A class can implement multiple interfaces.
Default and Static Methods in Interfaces
Beginning with Java 8, interfaces have the capability to include default and static methods with predefined implementations. Default methods enable the addition of new methods to an interface without causing disruption to existing implementations.
Inheritance with Interfaces
A class can extend another class and implement multiple interfaces simultaneously. When extending a class and implementing interfaces, the extends keyword comes before the implements keyword.
In this example;
- We define two interfaces, Shape and Drawable, each with one or more methods.
- We create a parent class Parent with a display method.
- The Child class extends Parent (inheritance from a class) and implements both Shape and Drawable interfaces. It provides concrete implementations for the methods defined in the interfaces.
- In the main method, we create an instance of the Child class and demonstrate how to call methods from both interfaces and the parent class.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP