美团笔试题 -- 类初始化顺序 (记录下)

class Father{
    private String a = "father";
    public Father(){
        say();
    }
    public void say(){
        System.out.println("i'm father"+a);
    }
}
class Sub extends Father{
    private String a = "child";
    @Override
    public void say(){
        System.out.println("i'm child"+a);
    }
}
public class Test03 {
    public static void main(String[] args) {
        Father father = new Father(); //输出 -> i'm fatherfather
        Sub sub = new Sub();  //输出 -> i'm childnull
        //当创建子类时,首先会去加载父类,但由于say方法已经被子类重写,所以父类的构造方法调用的是子类的say
        //此时由于子类还未初始化完成,子类的a是null状态,自然在父类调用时就会输出"i'm childnull"
        //当父类构造方法调用完成后,才回去初始化子类,此时的a就等于"child"
    }
}
posted @ 2021-08-25 23:32  hehell  阅读(59)  评论(0)    收藏  举报