How can interfaces replace the need for multiple inheritance when have existing classes

后端 未结 10 988
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:48

First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not

10条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:27

    Similar to what Andreas_D suggested but with the use of inner classes. This way you indeed extend each class and can override it in your own code if desired.

    interface IBird {
        public void layEgg();
    }
    
    interface IMammal {
        public void giveMilk();
    }
    
    class Bird implements IBird {
        public void layEgg() {
            System.out.println("Laying eggs...");
        }
    }
    
    class Mammal implements IMammal {
        public void giveMilk() {
            System.out.println("Giving milk...");
        }
    }
    
    class Platypus implements IMammal, IBird {
    
        private class LayingEggAnimal extends Bird {}
        private class GivingMilkAnimal extends Mammal {}
    
        private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
    
        private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
    
        @Override
        public void layEgg() {
            layingEggAnimal.layEgg();
        }
    
        @Override
        public void giveMilk() {
            givingMilkAnimal.giveMilk();
        }
    }
    

提交回复
热议问题