package test;
public class testStatic {
public static void main(String[] args) {
A a=new B();
a=new B();
}
}
class A{
static{
System.out.println("static a");
}
public A()
{
System.out.println("A");
}
}
class B extends A{
static{
System.out.println("static b");
}
public B()
{
System.out.println("B");
}
}
输出结果:
static a
static b
A
B
A
B
我发现好多公司笔试题都喜欢考这种
静态代码块在加载类之后马上执行。
类在第一次用到的时候被加载。
A a=new B();
所以先加载A.class,然后加载B.class。所以先输出了static a,然后是static b。
接下来代码执行new B();
会调用B的构造函数。
B的构造函数第一句会默认调用父类的无参构造函数。
所以会输出A,B。
由于第二次又执行了new B();
所以会再次输出A,B。