Java Multiple Inheritance

前端 未结 17 1550
猫巷女王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:32

    Ehm, your class can be the subclass for only 1 other, but still, you can have as many interfaces implemented, as you wish.

    A Pegasus is in fact a horse (it is a special case of a horse), which is able to fly (which is the "skill" of this special horse). From the other hand, you can say, the Pegasus is a bird, which can walk, and is 4legged - it all depends, how it is easier for you to write the code.

    Like in your case you can say:

    abstract class Animal {
       private Integer hp = 0; 
       public void eat() { 
          hp++; 
       }
    }
    interface AirCompatible { 
       public void fly(); 
    }
    class Bird extends Animal implements AirCompatible { 
       @Override
       public void fly() {  
           //Do something useful
       }
    } 
    class Horse extends Animal {
       @Override
       public void eat() { 
          hp+=2; 
       }
    
    }
    class Pegasus extends Horse implements AirCompatible {
       //now every time when your Pegasus eats, will receive +2 hp  
       @Override
       public void fly() {  
           //Do something useful
       }
    }
    

提交回复
热议问题