天下脸皮共十分
我占八分

类加载顺序


静态代码块:用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
赞(1) 打赏
未经允许不得转载:Stephen Young » 类加载顺序
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏