Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

后端 未结 18 2075
囚心锁ツ
囚心锁ツ 2020-11-22 14:55

Java doesn\'t allow multiple inheritance, but it allows implementing multiple interfaces. Why?

18条回答
  •  甜味超标
    2020-11-22 15:15

    The answer of this question is lies in the internal working of java compiler(constructor chaining). If we see the internal working of java compiler:

    public class Bank {
      public void printBankBalance(){
        System.out.println("10k");
      }
    }
    class SBI extends Bank{
     public void printBankBalance(){
        System.out.println("20k");
      }
    }
    

    After compiling this look like:

    public class Bank {
      public Bank(){
       super();
      }
      public void printBankBalance(){
        System.out.println("10k");
      }
    }
    class SBI extends Bank {
     SBI(){
       super();
     }
     public void printBankBalance(){
        System.out.println("20k");
      }
    }
    

    when we extends class and create an object of it, one constructor chain will run till Object class.

    Above code will run fine. but if we have another class called Car which extends Bank and one hybrid(multiple inheritance) class called SBICar:

    class Car extends Bank {
      Car() {
        super();
      }
      public void run(){
        System.out.println("99Km/h");
      }
    }
    class SBICar extends Bank, Car {
      SBICar() {
        super(); //NOTE: compile time ambiguity.
      }
      public void run() {
        System.out.println("99Km/h");
      }
      public void printBankBalance(){
        System.out.println("20k");
      }
    }
    

    In this case(SBICar) will fail to create constructor chain(compile time ambiguity).

    For interfaces this is allowed because we cannot create an object of it.

    For new concept of default and static method kindly refer default in interface.

    Hope this will solve your query. Thanks.

提交回复
热议问题