How to Simulate Multiple Inheritance in Java

admin  

Java or .NET languages does not allow multiple inheritance and usually we don't need multiple inheritance in our projects. However there are cases when inheriting from multiple classes is a necessity. There are a few tricks we can apply in order to be able to get what multiple inheritance gives us in the languages where it is supported.

The great idea to achieve it is to use delegation instead of inheritance. Let's consider we already have to classes we want to extend. We can use the inheritance so our new class will extend the first class. For the second class we can not use inheritance again, because we already inherit the first one, on the other side we want to overwrite some method implementations. The trick is to create an inner class extending the second class, and to delegate the calls from the main outer class to the inner class.

The technique can be "scaled" for any number of classes. For each new class which we need to inherit, we need to create another inner class and delegate the request to it. The big drawback here is the amount of code that should be written for creating the inherited inner classes and the code for delegating all the requests which which in case of multiple inheritance are done by default.