java-类的加载流程

复制代码
 1 public class F {
 2     static {
 3         System.out.println("f static");
 4     }
 5 
 6     private static int a = me();
 7 
 8     private static int me() {
 9         System.out.println("f static field");
10         return 1;
11     }
12 
13     public F() {
14         System.out.println("f cons");
15     }
16 }
17 
18 ---
19 public class S extends F {
20     static {
21         System.out.println("s static");
22     }
23 
24     private static int s = mew();
25 
26     private static int mew() {
27         System.out.println("s static field");
28         return 0;
29     }
30 
31 
32     public S() {
33         System.out.println("s cons");
34     }
35 
36     public static void main(String[] args) {
37         System.out.println("a main");
38         S s = new S();
39     }
40 }
复制代码

执行结果

f static
f static field
s static
s static field
a main
f cons
s cons

类在加载的时候先执行静态部分的代码,先执行静态代码块还是静态字段 需要根据顺序来执行,谁排前边谁先执行

posted @   rudynan  阅读(72)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示