Why are class static methods inherited but not interface static methods?

后端 未结 5 1710
南旧
南旧 2020-11-29 00:22

I understand that in Java static methods are inherited just like instance methods, with the difference that when they are redeclared, the parent implementations are hidden r

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 00:43

    Let's begin with some background ...

    Java doesn't support multiple inheritance (the ability to extend more than one class). This is because multiple inheritance is prone to the deadly diamond of death (also known as the diamond problem) which the designers of Java chose to preempt.

    If B and C override a method inherited from A, which method does D inherit?

    A class can implement multiple interfaces because interface methods are contracted for overriding; if a class C implements two interfaces A and B that declare the same method, then the same method in C will be invoked by clients of either interface (A or B). The introduction of default methods for interfaces in Java 8 was made possible by forcing the implementer to override the default in case of ambiguity. This was an acceptable compromise since default methods are intended to be defensive (to be used if no other implementation is explicitly provided by an implementer). However, since the compiler can’t force you to override a static method (static methods inherently can't be overridden), the introduction of static methods for interfaces in Java came with one restriction: the static methods of an interface are not inherited.

提交回复
热议问题