Implementation of multiple inheritance in Java

In this article we demonstrate how multiple inheritance can be implemented easily in Java.

Sometimes you need that a certain class behave much like two or more base classes. As Java does not provide multiple inheritance, we have to circumvent this restriction somehow. The idea consists of:

At this point, extended classes of your given class can now implement the interface you have created, instead of extending your class. Some more steps ate necessary:

For example, imagine that you have

interface A {
    void methodA();
}

interface B {
    void methodB();
}

class ClassA implements A {
    void methodA() { /* do something A */ }
}

class ClassB implements B {
    void methodB() { /* do something B */ }
}

class ClassC implements A, B {

    // initialize delegates
    private final A delegateA = new ClassA();
    private final B delegateB = new ClassB();

    // implements interface A
    @Override
    void methodA() {
        delegateA.methodA();
    }

    // implements interface B
    @Override
    void methodB() {
        delegateB.methodB();
    }
}

If you found this article useful, it will be much appreciated if you create a link to this article somewhere in your website. Thanks