代码如下:
public class ParentDemo {
static {
System.out.println("this is ParentDemo static");
}
{
System.out.println("this is ParentDemo code block");
}
public ParentDemo() {
System.out.println("this is ParentDemo constructor");
}
}
public class SonDemo extends ParentDemo{
static {
System.out.println("this is SonDemo static");
}
{
System.out.println("this is SonDemo code block");
}
public SonDemo() {
System.out.println("this is SonDemo constructor");
}
}
public class TestMain {
public static void main(String[] args){
new SonDemo();
}
}
输出结果:
this is ParentDemo static
this is SonDemo static
this is ParentDemo code block
this is ParentDemo constructor
this is SonDemo code block
this is SonDemo constructor
由上可见,Java中 静态块中的代码在类加载时执行,子类继承父类。会按照继承的顺序先执行静态代码块。当实例化对象的时候,同理会按照继承的顺序依次执行如下代码:
代码块,构造函数,当父类的执行完以后,再执行子类。
总结:
第一次写博客,略显青涩。