静态代码块:用staitc声明,jvm加载类时执行,仅执行一次
构造代码块:类中直接用{}定义,每一次创建对象时执行。
执行顺序优先级:静态块,main(),构造块,构造方法。
父类
package tech.ityoung.study.demo.jvm;
public class Father {
static {
System.out.println("this is static block from father");
}
{
System.out.println("this is block from father");
}
public Father() {
System.out.println("this is contractor from father");
}
}
子类
package tech.ityoung.study.demo.jvm;
public class Son extends Father {
static {
System.out.println("this is static block from son");
}
{
System.out.println("this is block from son");
}
public Son() {
System.out.println("this is contractor from son");
}
public static void main(String[] args) {
System.out.println("true = " + true);
}
}
测试类
package tech.ityoung.study.demo.jvm;
public class ExtendsTest {
public static void main(String[] args) {
System.out.println("son is not born");
Son son = new Son();
System.out.println("son = " + son);
}
}
运行结果
son is not born
this is static block from father
this is static block from son
this is block from father
this is contractor from father
this is block from son
this is contractor from son
son = tech.ityoung.study.demo.jvm.Son@4157f54e
评论前必须登录!
注册