Middle
How can multiple inheritance be implemented in Java?
sobes.tech AI
Answer from AI
Multiple inheritance of class implementations in Java is not directly supported due to the "diamond problem." However, its functionality can be achieved through the following methods:
-
Interfaces: A class can implement multiple interfaces. Interfaces only define method signatures, not their implementation.
interface InterfaceA { void methodA(); } interface InterfaceB { void methodB(); } class MyClass implements InterfaceA, InterfaceB { @Override public void methodA() { // Implementation of methodA } @Override public void methodB() { // Implementation of methodB } }With the introduction of default methods in Java 8, interfaces can also provide default implementations.
interface InterfaceC { default void defaultMethod() { System.out.println("Default implementation"); } } class MyClass2 implements InterfaceC { // Can use defaultMethod or override it } -
Composition: Instead of inheriting from multiple classes, a class can contain instances of other classes (members).
class ComponentA { void methodA() { // Implementation of methodA } } class ComponentB { void methodB() { // Implementation of methodB } } class MyClass3 { private ComponentA compA = new ComponentA(); private ComponentB compB = new ComponentB(); public void delegateMethodA() { compA.methodA(); } public void delegateMethodB() { compB.methodB(); } }The class
MyClass3delegates method calls to the objectscompAandcompB.
Comparison:
| Mechanism | Implementation inheritance | Diamond problem | Flexibility |
|---|---|---|---|
| Interfaces | No (before default) | No | High |
| Composition | Yes | No | High |