This article will demonstrate the method to implement multiple interfaces.
Can a Java Class Implement Multiple Interfaces?
Yes, multiple interfaces can be implemented which allows a class to provide implementations for the methods declared in multiple interface types. But users must confirm that all the required methods are implemented correctly for each interface.
Syntax
To implement multiple interfaces in Java, users need to use the following basic syntax:
// class body
}
The description of the above syntax is mentioned below:
- MyClass is the name of the class that implements multiple interfaces.
- Interface1, Interface2, and Interface3 are the names of the interfaces which the class is implemented in.
Note: If users want to implement more interfaces, simply separate them with commas.
Example
This example shows how a class can implement multiple interfaces to provide different sets of functionalities, and how instances of the class can be used to perform specific tasks.
Here is an example of a Java class that implements multiple interfaces:
double getArea();
}
interface Printable {
void print();
}
class Rectangle implements Shape, Printable {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public void print() {
System.out.println("Rectangle with length " + length + " and width " + width);
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 10);
rect.print(); // output: Rectangle with length 5.0 and width 10.0
System.out.println("Area: " + rect.getArea()); // output: Area: 50.0
}
}
The explanation of the above code is given below:
- First, we have two interfaces: “Shape” and “Printable”. The “Shape” interface defines a method “getArea()” that returns the area of a shape,
- While the “Printable” interface defines a method “print()” that prints some information about the shape.
- After that, a class “Rectangle” that implements both interfaces. It has a constructor that accepts two double arguments “length” and “width”.
- It provides implementations for the “getArea()”, and “print()” methods declared in the “Shape” and “Printable” interfaces, respectively.
- In the main() method, create an instance of “Rectangle” with length “5” and width “10”, and call its print() and getArea() methods.
Output
The output of the program returns to the “Area: 50.0” in the terminal.
Conclusion
In Java, a class can implement multiple interfaces by specifying all the interface names in the class declaration’s “implements” clause, separated by commas. After that, the class offers executions for all the declared methods in interfaces. It allows the class to inherit behavior from multiple sources and provides a versatile and flexible design. This guide has explained the implementations for all the methods declared in each interface.