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

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

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

18条回答
  •  悲哀的现实
    2020-11-22 15:23

    You can find accurate answer for this query in oracle documentation page about multiple inheritance

    1. Multiple inheritance of state: Ability to inherit fields from multiple classes

      One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes

      If multiple inheritance is allowed and When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. It will cause two issues.

      1. What if methods or constructors from different super classes instantiate the same field?
      2. Which method or constructor will take precedence?
    2. Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes

      Problems with this approach: name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.

      But java supports this type of multiple inheritance with default methods, which have been introduced since Java 8 release. The Java compiler provides some rules to determine which default method a particular class uses.

      Refer to below SE post for more details on resolving diamond problem:

      What are the differences between abstract classes and interfaces in Java 8?

    3. Multiple inheritance of type: Ability of a class to implement more than one interface.

      Since interface does not contain mutable fields, you do not have to worry about problems that result from multiple inheritance of state here.

提交回复
热议问题