Sobes.tech
Middle

How can multiple inheritance be implemented in Java?

sobes.tech AI

Answer from AI

Directly — not at all. Java does not support multiple inheritance of classes to avoid the diamond problem.

Multiple inheritance of behavior (implementing multiple interfaces) is possible.

// Example of implementing multiple interfaces
public interface InterfaceA {
    void methodA();
}

public interface InterfaceB {
    void methodB();
}

public class MyClass implements InterfaceA, InterfaceB {
    @Override
    public void methodA() {
        // Implementation of methodA
    }

    @Override
    public void methodB() {
        // Implementation of methodB
    }
}

For a certain resemblance of multiple inheritance of functionality, you can use:

  • Interfaces with default and static methods (Java 8+): Allow providing default implementations of methods in interfaces.

    public interface InterfaceWithDefaults {
        default void defaultMethod() {
            System.out.println("Default implementation");
        }
        static void staticMethod() {
            System.out.println("Static method");
        }
    }
    
    public class AnotherClass implements InterfaceWithDefaults {
        // Uses defaultMethod from the interface
        // Or can override it
    }
    
  • Composition: A class contains instances of other classes and delegates method calls to them. This is the preferred approach for "has-a" relationship instead of "is-a".

    public class FeatureA {
        public void doFeatureA() {
            System.out.println("Doing feature A");
        }
    }
    
    public class FeatureB {
        public void doFeatureB() {
            System.out.println("Doing feature B");
        }
    }
    
    public class CombinedClass {
        private FeatureA featureA = new FeatureA();
        private FeatureB featureB = new FeatureB();
    
        public void performCombinedAction() {
            featureA.doFeatureA();
            featureB.doFeatureB();
        }
    }
    

Comparison of approaches:

Approach Multiple inheritance of state Multiple inheritance of behavior Diamond problem solution
Class inheritance No Yes (single base class) Solved
Interface implementation No Yes Not applicable
Interfaces with default/static No Yes Solved (explicit call)
Composition Yes No (delegation) Not applicable
How can multiple inheritance be implemented in Java… - sobes.tech