1、java官方教程里有一段话,解释了原因: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. For example, suppose that you are able to define a new class that extends multiple classes. When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. What if methods or constructors from different superclasses instantiate the same field? Which method or constructor will take precedence? Because interfaces do not contain fields, you do not have to worry about problems that result from multiple inheritance of state.http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html2、问题是这段话我没看懂啊,我操。真的认认真真看了,而且这个教程一节一节看下来,没看懂的地方实在不多啊——可是这么关键性的这一段,居然看不懂啊我操。3、大伙都抡起袖子来解释一番呗~
3 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
public Class A 有 public int i=0, some() {i=1;}
public Class B 有 public int i=0, some() {i=2;}
public Class C 有 public int i=0, extends A,B
现在C实例化c,执行c.some(), i=?
不允许继承多类,就是为了避免继承多父类,在调用相同方法或者构造函数时赋值同一个成员变量时,凌乱了...
长风秋雁
TA贡献1757条经验 获得超7个赞
说一下我的理解,有误请指出
不允许多重extends的理由是为了避免多重继承,如果允许多重继承,那么就可以获得多个被继承者的变量。假如你定义一个类继承多个class, 当你通过创建方法获得一个实例时,这个实例会得到所有被它extends也就是所有父类的变量/方法,如果多个父类有同一个变量,那将造成混乱。接口没有变量,则没有以上的矛盾。
添加回答
举报
0/150
提交
取消