Java Multiple Inheritance

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

    To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

    Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

    Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

    class A {  
        void msg() {
            System.out.println("From A");
        }  
    }
    
    class B {  
        void msg() {
            System.out.println("From B");
        }  
    }
    
    class C extends A,B { // suppose if this was possible
        public static void main(String[] args) {  
            C obj = new C();  
            obj.msg(); // which msg() method would be invoked?  
        }
    } 
    

提交回复
热议问题