Posted on 2013-07-21 15:20 
云云 阅读(316) 
评论(0)  编辑  收藏  
			 
			
		 
		当一个类中有声明为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);  
-     }  
- }  
因为a是static final变量,且它等于6/3,在编译的时候就可以知道它的值,所以直接访问a的值不会引起FinalTest类的初始化。作为表现,也就是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);  
-     }  
- }  
这个static final变量a因为i在编译的时候无法知道它的确切的值,所以只有等到运行的时候才能知道,所以自己访问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);  
-           
-     }  
- }  
因为直接访问Child,b,会先初始化Parent类,然后初始化Child类。
运行结果为
- 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类的a变量,则只会直接初始化parent类,不会初始化Child类
运行结果如下
- Parent static block  
- 3