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:
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?
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.
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 {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With