search

Home  >  Q&A  >  body text

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、大伙都抡起袖子来解释一番呗~

PHPzPHPz2887 days ago626

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:32:02

    public Class A has public int i=0, some() {i=1;}
    public Class B has public int i=0, some() {i=2;}
    public Class C has public int i=0 , extends A,B
    Now C instantiates c, executes c.some(), i=?
    Inheriting multiple classes is not allowed, just to avoid inheriting multiple parent classes and assigning the same member variable when calling the same method or constructor It was messy...

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:32:02

    Tell me my understanding, please point out if I am wrong
    The reason why multiple extends is not allowed is to avoid multiple inheritance. If multiple inheritance is allowed, then you can get the variables of multiple inheritees. If you define a class that inherits multiple classes, when you obtain an instance through the creation method, this instance will get all the variables/methods that it extends, that is, all parent classes. If multiple parent classes have the same variable, then Cause confusion. If the interface has no variables, there is no above contradiction.

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:32:02

    In addition to what is mentioned above, single inheritance can also avoid the diamond problem caused by multiple inheritance.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:32:02

    I think inheritance should reflect the characteristics (properties) and behaviors (methods) that an object should have.
    Think in terms of object-oriented programming:
    The parent class collects all the common characteristics and behaviors of the child class.
    The subclass has all the "public" features and behaviors of the parent class.
    This reflects the hierarchical structure between classes, and also solves the problem of describing the system in code.
    The above is purely for personal understanding. If there is any misleading, please accept the advice.
    Reference material: Java Programming 4th Edition

    reply
    0
  • Cancelreply