Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance without multiple inheritance and without code duplication

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?

like image 257
Levi Botelho Avatar asked May 27 '12 12:05

Levi Botelho


2 Answers

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.

like image 96
Tudor Avatar answered Sep 21 '22 06:09

Tudor


The more general term for this is a Mixin. Some languages provide support out of the box, such as Scala and D. There are various ways to achieve the same results in other languages though.

One way you can create a pseudo-mixin in C# is to use empty interfaces and provide the methods with extension methods.

interface A { }
static class AMixin {
    public static void aFunc(this A inst) {
        ... //implementation to work for all A.
    }
}

interface B { }
static class BMixin {
    public static void bFunc(this B inst) {
        ...
    }
}

class Qux : Foo, A, B {
    ...
}
like image 27
Mark H Avatar answered Sep 23 '22 06:09

Mark H