首页 > java里的类:为什么只能继承一个类,而可以实现多个接口?

java里的类:为什么只能继承一个类,而可以实现多个接口?

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.html

2、问题是这段话我没看懂啊,我操。
真的认认真真看了,而且这个教程一节一节看下来,没看懂的地方实在不多啊——可是这么关键性的这一段,居然看不懂啊我操。

3、大伙都抡起袖子来解释一番呗~


我觉得 继承 应该是体现一个对象应有的特征(属性)和行为(方法)。
按照面向对象编程方式思考:
父类集合了子类的所有共同特征和行为。
子类拥有父类的所有"公共"的特征和行为。
这样体现了一个类之间的层次结构,也解决了对系统的描述过度到用代码对系统进行描述。
以上个人纯属理解。如有误导,接受指点。
参考资料:java面向编程第4版


说一下我的理解,有误请指出
不允许多重extends的理由是为了避免多重继承,如果允许多重继承,那么就可以获得多个被继承者的变量。假如你定义一个类继承多个class, 当你通过创建方法获得一个实例时,这个实例会得到所有被它extends也就是所有父类的变量/方法,如果多个父类有同一个变量,那将造成混乱。接口没有变量,则没有以上的矛盾。


除了上面讲到的,单继承还可以避免多继承带来的钻石问题。


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=?
不允许继承多类,就是为了避免继承多父类,在调用相同方法或者构造函数时赋值同一个成员变量时,凌乱了...

【热门文章】
【热门文章】