Java Multiple Inheritance

前端 未结 17 1456
猫巷女王i
猫巷女王i 2020-11-22 09:36

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

17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 10:20

    There are two fundamental approaches to combining objects together:

    • The first is Inheritance. As you have already identified the limitations of inheritance mean that you cannot do what you need here.
    • The second is Composition. Since inheritance has failed you need to use composition.

    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:

    • Bird extends Animal implements IFlier
    • Horse extends Animal implements IHerbivore, IQuadruped
    • Pegasus extends Animal implements IHerbivore, IQuadruped, IFlier

    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.

提交回复
热议问题