Object-Oriented Design – Replacing Multiple Inheritance with Delegation

multiple-inheritanceobject-orientedobject-oriented-design

I was going through "Object Oriented Modelling and Design" by James Rumbaugh et al and it said that in languages where multiple inheritance is not supported like Java three mechanisms can be used as workarounds

  1. Delegation using aggregation of roles
  2. Inherit the most important
  3. class and delegate the rest Nested Generalization

I couldnt understand the examples given in the text. Could any one please explain this with an example. I know that "diamond problem" is a problem within multiple inheritance and java supports multiple inheritance of interfaces.

Best Answer

My observation is that a lot of folk misuse multiple inheritance without working through composition type questions.

The "classic" OO example of a car leads to this problem. For example, we'll say that a car breaks down to the following parts:

  • it's a vehicle
  • there are tires
  • there is an engine
  • there is a chassis
  • there are seats
  • and so on...

so we'll define a class that looks like this:

 public class Car : Vehicle, Tires, Engine, Chassis, Seats {}

All well and good, but it presents some significant problems with encapsulation and constructors / destructors. And it doesn't accurately represent what a car looks like in the real world.

If we start asking composition questions then we'll see some nuances here that weren't at first obvious.

  • is a car a vehicle? (yes)
  • is a car a tire or set of tires? (no, it has a set of tires)
  • is a car an engine? (no)
  • is a car a seat? (no)
  • etc ...

So now our class can look something like this:

public class Car : Vehicle
{
   public Tires tires;  //ie, myCar _has_ a set of tires.
   protected Engine engine;
   private Chassis chassis;
   protected Seats seats;
}

Which is also all well and good. But now we start scratching our heads and say "you know, I really wish that when I instantiate a car that it has to have tires, an engine, and a chassis."

So now we can turn Tires, Engine, and Chassis into interfaces and we'll have the following class. I'm prefixing the interfaces with "I" to make the distinction more clear.

public class Car : Vehicle, ITires, IEngine, IChassis
{
   protected Seats seats;
}

Interfaces are like contracts. When a class implements an interface, it's guaranteeing it will provide certain methods and behaviors.

And now things really are all well and good. Our model of the car accurately reflects the real world representation of the same Object, including some guarantees about the resemblance between the two courtesy of the Interfaces. We have avoided the icky issues that multiple inheritance can create.

That's not to say that multiple inheritance is always bad. However, it's not really needed most of the time which is why languages like Java and C# don't allow for multiple inheritance.

Related Topic