Multiple inheritance without multiple inheritance and without code duplication

c#, inheritance, java, oop

Solution

Well the only way I can see you achieving this in C#/Java is by composition. Consider this:

class Foo {

}

interface A {
    public void a();
}

interface B {
    public void b();
}

class ImplA implements A {
    @Override
    public void a() {
        System.out.println("a");
    }
}

class ImplB implements B {
    @Override
    public void b() {
        System.out.println("b");
    }
}

class Bar extends Foo {
    A a = new ImplA();

    public void a() {
        a.a();
    }
}

class Baz extends Foo {
    B b = new ImplB();

    public void b() {
        b.b();
    }       
}

class Qux extends Foo {

    A a = new ImplA();
    B b = new ImplB();

    public void b() {
        b.b();
    }

    public void a() {
        a.a();          
    }       
}

Now `Qux` has both the functionality of `Foo` via normal inheritance but also the implementations of `A` and `B` by composition.

Problem

I have a theoretical question concerning how to deal with the following scenario in a language which does not allow multiple inheritance. Imagine I have a base class Foo and from it I am wishing to create three sub-classes: - Class Bar inherits Foo and implements functionality "A" - Class Baz inherits Foo and implements functionality "B" - Class Qux inherits Foo and implements functionalities "A" and "B" Imagine that the code to implement functionalities "A" and "B" is always the same. Is there a way to write the code for "A" and "B" only once, and then have the appropriate classes apply (or "inherit") it?

Original source