How to simulate Multiple Inheritance in Java

  by Ronald Koster, version 1.0, 2004-05-06


Keywords: multiple inheritance, Java

Inherit from both

Suppose you want build a class X which you want to inherit from 2 other classes A and B. Choose one of them, for instance A, to extend. Then how do we arrange the inheritance from B?

Define an interface Bif as follows:

public interface Bif {
   public B getB();
   public void setB(B aB);
}
Then define class X as:
public class X extends A implements Bif {
   private B b;

   public B getB() {return b;}
   public void setB(B aB) {b = aB;}

   ... other code ...
}
Now when in some code we want to use members of X inherited from B:
   ...
   X x = new X();
   x.setB(new B());
   ...
   x.getB().mmm(...);  // Accessing member method B#mmm(...).
   ...

Accessing protected members

Now what if B has protected members you want to access within X and B is from another package?

Extend the above approach as follows. Introduce an extension of B called Bx:

public class Bx extends B {}
And modify Bif:
public interface Bif {
   public Bx getB();
   public void setB(Bx aB);
}
And modify X:
public class X extends A implements Bif {
   private Bx b;

   public Bx getB() {return b;}
   public void setB(Bx aB) {b = aB;}

   ... other code ...
}
The above example in which the member B#mmm(...) is accessed should now also work in case B#mmm(...) is a protected member.