父类与子类之间构造方法的调用关系

程序源代码:

class Grandparent {

public Grandparent() {
System.out.println("GrandParent Created.");
}

public Grandparent(String string) {
System.out.println("GrandParent Created.String:" + string);
}
}

class Parent extends Grandparent {

public Parent() {
// super("Hello.Grandparent.");
System.out.println("Parent Created");
// super("Hello.Grandparent.");
}
}

class Child extends Parent {

public Child() {
System.out.println("Child Created");
}
}

public class TestInherits {

public static void main(String args[]) {
Child c = new Child();
}
}

运行结果截图:

 加上super("Hello.Grandparent.");代码,运行结果截图:

原因分析:

有继承类的情况下,在进行方法调用或函数构造时系统会先构造基类在构造父类最后在构造子类

通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

原文地址:https://www.cnblogs.com/aishangtaxuefeihong/p/4936976.html