Java super()inheritance
这个问题的简短摘要:我有一个由子类扩展的父类。
public class Parent{ public Parent(){ //constructor logic } }
这个子类使用super调用Parent的构造函数:
public class Child extends Parent{ public Child(){ super(); } }
如果我可以在Grandchild类的构造函数中调用super()方法,我想知道是否要扩展Child类:
public class Grandchild extends Child{ public Grandchild(){ super(); } }
super()在inheritance上调用构造函数一级,如果有一个无参数构造函数,则隐式调用它。
对象从最高级别的inheritance初始化,在您的情况下,它是对象>父>子>孙。
从文档 :
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
这将调用Child
类构造函数,而后者将调用Parent
类构造函数。