运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!
源代码:
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();
}
}
运行结果:
改变parent类:
结果截图:
结论:
通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。
为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?
构造函数的作用是初始化对象,类继承了父类,就默认含有父类的公共成员方法和公共成员变量,这些不再子类中重复声明。而构造方法则相当于把父类给实例化出来,如果子类实例化的时候不调用父类的构造方法,相当于子类压根就没有父亲。不能反过来。
在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。
源代码:
class Jiaqin {
public void show() {
System.out.println("家禽!");
}
}
class Yazi extends Jiaqin {
public void show() {
System.out.println("鸭子!");
super.show();
}
}
public class Diaoyong {
public static void main(String[] args) {
Yazi a = new Yazi();
a.show();
}
}结果截图: