Java Multiple Inheritance

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

    Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.

    If you want to combine the functionality of two classes into one - use object composition. I.e.

    public class Main {
        private Component1 component1 = new Component1();    
        private Component2 component2 = new Component2();
    }
    

    And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.

    Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define

    class Main implements Interface1, Interface2
    

    So that you can use objects interchangeably where the context allows it.

    So in my point of view, you can't get into diamond problem.

提交回复
热议问题