Multiple inheritance on Java interfaces

后端 未结 5 2014
暖寄归人
暖寄归人 2020-12-09 08:28

I thought multiple inheritance was always illegal in Java, but this code compiles:

public interface A {
  void a();
}

public interface B {
  void b();
}

pu         


        
5条回答
  •  一生所求
    2020-12-09 09:15

    In this related question, Jay provides an answer to this. The difference is specifying the implementation versus the interface.

    The issue with the implementation only occurs when two functions have the same name. This is because there is no obvious choice to the question "What implementation of f() do I use?" with multiple implementations.

    The issue does not occur with two interfaces of the same function name because it does not need to make this selection. Rather, you are just required to implement your own version of the function at hand.

    As an example, we can look at a counterpart that does allow multiple inheritance - C++. This link explains things well, and provides some code/image examples. One thing to notice is that since you are required to explicitly scope what class a function belongs to anyway, you can easily mitigate the issue in C++.

    In Java however, we really never have to do this (since there are only methods which are attached to objects, if you will), As a result don't have a method to scope the call. The only options we have to refer to a parent class is by using the super keyword, or by use of a static function. As a result, there would be no clear option to resolve this in Java, barring additional changes to the system, for little gain.

提交回复
热议问题