class A{
    static{
        System.out.print("1");
    }
    public A(){
        System.out.print("2");
    }
}
class B extends A{
    static{
        System.out.print("a");
    }
    public B(){
        System.out.print("b");
    }
}

public class Hello{
    public static void main(String[] args){
        A ab = new B();
        ab = new B();
    }
}

执行结果:1a2b2b。
创建对象时构造器的调用顺序是:首先初始化父类静态成员,然后初始化子类静态成员(静态成员只在类第一次被加载时初始化一次),然后调用父类构造器,再初始化非静态成员,最后调用自身构造器。

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.