Multiple Inheritance Ambiguity with Interface

前端 未结 6 2203
轮回少年
轮回少年 2020-12-24 12:48

We all know about the diamond problem regarding multiple inheritance -

   A
  / \\
 B   C
  \\ / 
   D

This problem describe an ambiguous

6条回答
  •  遥遥无期
    2020-12-24 13:24

    Java overcomes this problem even though interfaces can have default implementations of methods, because the default implementation is either unambiguous (the one in class A) or the situation is solved by some rule (when class B or class C overrides the implementation from class A, see below).

    When the supertypes of a class or interface provide multiple default methods with the same signature:

    • Instance methods are preferred over interface default methods.
    • Methods that are already overridden by other candidates are ignored. This circumstance can arise when supertypes share a common ancestor.

    However, if two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods. In this case you could invoke any of the of the default implementations with the super keyword.

    See also: How does Java 8' new default interface model works (incl. diamond, multiple inheritance, and precedence)?

提交回复
热议问题