问题的简短摘要:我有一个父类,并由子类扩展。
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()在继承上一级调用构造函数,如果存在无参数的构造函数,则将隐式调用该构造函数。
对象是从继承的最高层初始化的,在您的情况下是对象>父>子>孙。
从文档中:
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.