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

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

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

18条回答
  •  伪装坚强ぢ
    2020-11-22 15:35

    * This is a simple answer since I'm a beginner in Java *

    Consider there are three classes X,Y and Z.

    So we are inheriting like X extends Y, Z And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet. So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet??? So java is not supporting multiple inheritance. In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.

    So in a word, in Interfaces definition is done after implementation so no confusion.

提交回复
热议问题