源代码:
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调用基类构造方法,必须是子类构造方法中的第一个语句。
为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?
子类继承了父类所有的对象和成员变量,既然如此肯定要先初始化,才能正确使用父类的对象和成员变量。同样的,反过来说,父类并不知道会有什么子类,也不知道子类有什么特殊的对象和成员变量,自然也就无法提前初始化了。