In an attempt to fully understand how to solve Java\'s multiple inheritance problems I have a classic question that I need clarified.
Lets say I have class Ani
There are two fundamental approaches to combining objects together:
The way this works is that you have an Animal object. Within that object you then add further objects that give the properties and behaviors that you require.
For example:
Now IFlier
just looks like this:
interface IFlier {
Flier getFlier();
}
So Bird
looks like this:
class Bird extends Animal implements IFlier {
Flier flier = new Flier();
public Flier getFlier() { return flier; }
}
Now you have all the advantages of Inheritance. You can re-use code. You can have a collection of IFliers, and can use all the other advantages of polymorphism, etc.
However you also have all the flexibility from Composition. You can apply as many different interfaces and composite backing class as you like to each type of Animal
- with as much control as you need over how each bit is set up.
Strategy Pattern alternative approach to composition
An alternative approach depending on what and how you are doing is to have the Animal
base class contain an internal collection to keep the list of different behaviors. In that case you end up using something closer to the Strategy Pattern. That does give advantages in terms of simplifying the code (for example Horse
doesn't need to know anything about Quadruped
or Herbivore
) but if you don't also do the interface approach you lose a lot of the advantages of polymorphism, etc.