Java does not allow multiple inheritance.  This is a good thing because it simplifies the class hierarchy.  Most instances where multiple inheritance might traditionally apply in other languages are easily represented as “this class is of type A but also behaves like interface B and interface C”.

For example, a Lion type IS an Animal, but we also need it to behave like a Carnivore.  The Animal base class doesn't provide that ability.

public class Lion extends Animal
{
    :
}

But we can create a Carnivore interface.

public interface Carnivore
{
    String getHuntingMethod();
}

And implement it in the Lion:

public class Lion extends Animal implements Carnivore
{
    public String getHuntingMethod()
    {
        return "Stalks prey, non scavenger";
    }
    :
}

Later in the code you can check for the existence of the interface you want to get access to the other “inherited” attribute.

:
if (userAnimal instanceof Carnivore)
{
    userCarnivore = (Carnivore)userAnimal;
    :
}
:

So generally implement multiple inheritance using interfaces.

Tip: As an alternative to using interfaces for multiple inheritance, you can implement it by building a series of roles into a class.  For example, rather than having an interface called Carnivore, the Animal could behave in the role of Carnivore, one of many roles built into the Animal class.  An animal could have more than just the role=AnimalRole.CARNIVORE at one time.  e.g.  role=AnimalRole.CARNIVORE | AnimalRole.NOCTURNAL

blog comments powered by Disqus