public class Test001 {
public static void main(String[] args) {
new Child();
}
}
class Father{
private String name = "f";
public Father(){
tell();
}
public void tell(){
System.out.println("father "+this.name);
}
}
class Child extends Father{
private String name = "c";
public Child(){
tell();
}
public void tell(){
System.out.println("child "+name);
}
}
child null
child c
说明子类实例化,先实例化父类对象,即先将父类变量初始化,然后调用父类构造函数,不过此时如果父类构造器调用的被子类重写的方法,则调用的是子类的方法。此时的name也是子类的name,因为此时子类变量尚未实例化,所以值为null;
时间: 2024-08-28 06:58:21