Question
Can an interface in Java extend multiple other interfaces?
interface Foo extends Runnable, Set, Comparator<String> { }
Answer
Yes, an interface in Java can extend multiple interfaces. This capability provides a means for code reusability and design flexibility. It allows an interface to inherit abstract methods from multiple parent interfaces, thereby enabling polymorphism and multiple inheritance of types without the complexities associated with multiple inheritance in classes.
interface Serializable { }
interface Cloneable { }
interface CustomInterface extends Serializable, Cloneable {
void customMethod();
}
Causes
- Java permits multiple inheritance for interfaces, allowing one interface to inherit from several others.
- This design choice helps avoid the diamond problem, which is common in class-based inheritance.
- Interfaces in Java do not have state (no instance variables), which simplifies the implementation without the ambiguities tied to classes.
Solutions
- When defining an interface that extends multiple interfaces, separate the parent interfaces with a comma in the `extends` clause.
- Maintain clarity and cohesion; extend only interfaces that are logically related to avoid confusion.
- Ensure that the inherited methods do not have conflicting signatures among the parent interfaces.
Common Mistakes
Mistake: Attempting to extend both a class and an interface in the same definition.
Solution: Remember that a class can extend only one other class, but it can implement multiple interfaces.
Mistake: Confusing the `extends` and `implements` keywords when defining interfaces.
Solution: Use `extends` to extend other interfaces and `implements` when a class is implementing the behavior defined by interfaces.
Helpers
- Java interface multiple inheritance
- extend multiple interfaces in Java
- Java interface example
- Java programming tips
- Java inheriting interfaces