Can Interface Extend Another Interface in Java? Explained
Yes, in Java, an
interface can extend another interface using the extends keyword. This allows the child interface to inherit all abstract methods of the parent interface, enabling multiple levels of abstraction.Syntax
The syntax to make one interface extend another in Java is simple. Use the extends keyword followed by the parent interface name. You can extend multiple interfaces by separating them with commas.
- ChildInterface: The new interface that inherits methods.
- ParentInterface: The existing interface being extended.
java
public interface ParentInterface { void parentMethod(); } public interface ChildInterface extends ParentInterface { void childMethod(); }
Example
This example shows how ChildInterface extends ParentInterface. A class MyClass implements ChildInterface and must provide implementations for both parentMethod() and childMethod().
java
public interface ParentInterface { void parentMethod(); } public interface ChildInterface extends ParentInterface { void childMethod(); } public class MyClass implements ChildInterface { @Override public void parentMethod() { System.out.println("Parent method called"); } @Override public void childMethod() { System.out.println("Child method called"); } public static void main(String[] args) { MyClass obj = new MyClass(); obj.parentMethod(); obj.childMethod(); } }
Output
Parent method called
Child method called
Common Pitfalls
Some common mistakes when extending interfaces include:
- Trying to use
implementsinstead ofextendswhen one interface inherits another. - Forgetting that a class implementing the child interface must implement all methods from both interfaces.
- Attempting to extend a class with an interface, which is not allowed.
java
/* Wrong: Using implements instead of extends between interfaces */ // public interface ChildInterface implements ParentInterface { } // This causes a compile error /* Correct: Use extends */ public interface ChildInterface extends ParentInterface { }
Quick Reference
| Concept | Description |
|---|---|
| interface extends interface | Child interface inherits all methods from parent interface(s) |
| class implements interface | Class must implement all interface methods |
| multiple inheritance | Interface can extend multiple interfaces separated by commas |
| syntax | public interface Child extends Parent1, Parent2 { } |
Key Takeaways
An interface in Java can extend one or more interfaces using the extends keyword.
A class implementing a child interface must implement all methods from the entire interface hierarchy.
Use extends, not implements, when one interface inherits another interface.
Interfaces support multiple inheritance by extending multiple interfaces separated by commas.
Extending interfaces helps organize and reuse method declarations in Java.