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?
There are several ways to do something like this. More specifically, if we abandon the inheritance aspect for a moment, there are ways to introduce the same unit of functionality to different classes, while writing the unit only once.
Okay, I love AOP Frameworks, and they exist for many languages (C# and Java having several). AOP Frameworks basically allow you add self-contained functionality into different classes throughout your inheritance structure.
For C#, you have PostSharp and for Java you have AspectJ, among many others.
Many AOP frameworks allow 'hijacking' or 'overriding' method calls without using inheritance.
Well the only way I can see you achieving this in C#/Java is by composition. Consider this:
Now
Qux
has both the functionality ofFoo
via normal inheritance but also the implementations ofA
andB
by composition.This is achievable in languages providing traits (here: scala):
Because Scala runs on top of Java (having neither multiple inheritance nor traits) it is translated into something like this (simplified) - which might be a hint how to implement it in Java/C# manually:
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.