next up previous
Next: 2.3.1 General scheme Up: 2. Generics and Multiple Previous: 2.2.3 Using Java Reflection

2.3 Approximating Multiple Inheritance in Java

What does support for multiple inheritance accomplish for the following example, which is illegal in Java?

      class A { ...
        public    String a()  { return a1(); }
        protected String a1() { return "A";  }    

      class B { ...
        public    String b()  { return b1(); }
        protected String b1() { return "B";  }    

      class C extends A, B { ... 
        protected String a1() { return "C";  }     
        protected String b1() { return "C";  }     

Code Reuse:
The fields defined in classes A and B are present in an instance of class C, and a method defined in class A (resp. class B) can potentially be run on an instance of class C.
An instance of class C can potentially be used wherever an instance of class A (resp. class B) is required.

Inherited methods can be adapted to the needs of class C by overriding methods on which they rely. For instance, the definition of method a1() and b1() in C has the indirect effect that the inherited methods a() and b() now return "C".
Any changes to classes A and B are propagated automatically to class C.

Often, multiple inheritance is (mis)used for just one of the above effects, for example, just for code reuse or for achieving multiple subtyping. It is, therefore, important to understand how each effect can be simulated in Java and, even more, to assess which effects are relevant to a particular design.

In the following we will first present the general scheme for a simulation of multiple inheritance and identify the ingredients of the simulation that achieve each of the above effects. Then we will present different examples that illustrate how these ingredients can be used in various combinations. The examples will develop from cases that do not really require multiple inheritance (and are indeed better solved without), via cases where multiple inheritance would be appropriate (and can be approximated in Java), to cases where more dynamic techniques than multiple inheritance are required. We show that in the latter cases our simulation is preferable to multiple inheritance but it still cannot provide the full power that can be achieved by suitable language support. We conclude this section by contrasting our simulation with an extension of Java that provides support for multiple object-based inheritance.

next up previous
Next: 2.3.1 General scheme Up: 2. Generics and Multiple Previous: 2.2.3 Using Java Reflection
T. K. Prasad