Middle
How is multiple inheritance implemented in Java?
sobes.tech AI
Answer from AI
In Java, multiple inheritance of classes is not directly supported to avoid issues with the diamond problem and ambiguities. Instead, multiple inheritance is achieved through interfaces.
A class can implement multiple interfaces, each defining a set of methods. Starting from Java 8, interfaces can contain methods with implementations (default methods), which allows partial implementation of functionality.
Example:
interface A {
default void method() {
System.out.println("A");
}
}
interface B {
default void method() {
System.out.println("B");
}
}
class C implements A, B {
@Override
public void method() {
// Must explicitly specify which implementation to use
A.super.method();
}
}
Thus, multiple inheritance is achieved through interfaces with default methods and their explicit resolution in classes.