Question
Do default methods in JDK 8 represent a form of multiple inheritance in Java?
Answer
JDK 8 introduced default methods in interfaces, allowing developers to add new methods with default implementations without breaking existing code. This feature can resemble multiple inheritance since a class can implement multiple interfaces that provide default methods. However, Java still enforces specific rules to manage method resolution and avoid ambiguity when conflicts arise.
public interface Attendance {
default boolean present() { return true; }
}
public interface Timeline {
default boolean present() { return false; }
}
public class TimeTravelingStudent implements Attendance, Timeline {
@Override
public boolean present() { return Attendance.super.present(); } // Resolving ambiguity
}
TimeTravelingStudent student = new TimeTravelingStudent();
System.out.println(student.present()); // Outputs: true
Causes
- Default methods allow interfaces to evolve without affecting existing implementations.
- A class can implement multiple interfaces, each potentially providing a default method with the same signature.
Solutions
- If a class implements multiple interfaces with conflicting default methods, the compiler will require an explicit override of the method.
- You can resolve ambiguity by providing a concrete implementation in the class that implements the interfaces.
Common Mistakes
Mistake: Failing to override a method when implementing multiple interfaces with the same default method signature.
Solution: Always provide an explicit implementation of the default method to resolve any conflicts.
Mistake: Assuming default methods are the same as instance methods.
Solution: Understand that default methods are still part of the interface and follow interface rules.
Helpers
- JDK 8
- default methods
- multiple inheritance
- Java interfaces
- method resolution
- TimeTravelingStudent example