Published by: Dikshya
Published date: 30 Jun 2023
In most programming languages, including Java, interfaces cannot be directly extended like classes can. However, you can achieve a similar effect by creating a new interface that extends the existing interface. This is known as interface inheritance or subtyping.
When you extend an interface, the new interface inherits the methods and constants from the parent interface. You can then add additional methods or constants to the new interface, further specifying the behavior or contract.
Here's an example in Java to demonstrate extending an interface:
// Parent interface
interface Printable {
void print();
}
// Child interface extending the Printable interface
interface PrintableExtended extends Printable {
void printDetails();
}
// Class implementing the PrintableExtended interface
class MyClass implements PrintableExtended {
public void print() {
System.out.println("Printing...");
}
public void printDetails() {
System.out.println("Printing details...");
}
}
// Usage
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
// Accessing methods through the Printable interface
Printable printable = myObject;
printable.print();
// Accessing methods through the PrintableExtended interface
PrintableExtended printableExtended = myObject;
printableExtended.printDetails();
}
}
In this example, the Printable
interface declares the print()
method. The PrintableExtended
interface extends Printable
and adds the printDetails()
method.
The MyClass
class implements the PrintableExtended
interface, which means it must provide implementations for both the print()
and printDetails()
methods.
In the main()
method, you can see that you can access the print()
method through the Printable
interface and the printDetails()
method through the PrintableExtended
interface. This demonstrates how interface inheritance allows you to access different sets of methods based on the interface type you use.