当一个类中有声明为static final的变量,这样的变量对类的加载器有一定的影响,首先看看下面的例子。
package com.bird.classLoad; class FinalTest{ public static final int a = 6/3; static{ System.out.println("FinalTest static block"); } } public class Test3 { public static void main(String[] args) { System.out.println(FinalTest.a); } }
始化。作为表现,也就是static静态代码快不会被加载。
运行结果为
2
在看一个例子
package com.bird.classLoad; import java.util.Random; class FinalTest4{ public static final int a = new Random().nextInt(100); static{ System.out.println("FinalTest4 static block"); } } public class Test4 { public static void main(String[] args) { System.out.println(FinalTest4.a); } }
FinalTest4.a会引起FinalTest4类的初始化。也就是static静态代码快的加载。
运行结果为
FinalTest4 static block 82
package com.bird.classLoad; class Parent{ static int a = 3; static{ System.out.println("Parent static block"); } } class Child extends Parent{ static int b = 4; static{ System.out.println("Chind static block"); } } public class Test5 { public static void main(String[] args) { System.out.println(Child.b); } }
运行结果为
Parent static block Chind static block 4
package com.bird.classLoad; class Parent{ static int a = 3; static{ System.out.println("Parent static block"); } } class Child extends Parent{ static{ System.out.println("Chind static block"); } } public class Test5 { public static void main(String[] args) { System.out.println(Child.a); } }
运行结果如下
Parent static block 3