Final关键字对JVM类加载器的影响

当一个类中有声明为static final的变量,这样的变量对类的加载器有一定的影响,首先看看下面的例子。

  1. package com.bird.classLoad;  
  2.  
  3. class FinalTest{  
  4.       
  5.     public static final int a = 6/3;  
  6.       
  7.     static{  
  8.         System.out.println("FinalTest static block");  
  9.     }  
  10. }  
  11.  
  12. public class Test3 {  
  13.     public static void main(String[] args) {  
  14.         System.out.println(FinalTest.a);  
  15.     }  
  16. }  

因为a是static final变量,且它等于6/3,在编译的时候就可以知道它的值,所以直接访问a的值不会引起FinalTest类的初始化。作为表现,也就是static静态代码快不会被加载。

运行结果为

在看一个例子

  1. package com.bird.classLoad;  
  2.  
  3. import java.util.Random;  
  4.  
  5. class FinalTest4{  
  6.       
  7.     public static final int a = new Random().nextInt(100);  
  8.       
  9.     static{  
  10.         System.out.println("FinalTest4 static block");  
  11.     }  
  12. }  
  13.  
  14. public class Test4 {  
  15.  
  16.     public static void main(String[] args) {  
  17.         System.out.println(FinalTest4.a);  
  18.     }  
  19. }  

这个static final变量a因为i在编译的时候无法知道它的确切的值,所以只有等到运行的时候才能知道,所以自己访问FinalTest4.a会引起FinalTest4类的初始化。也就是static静态代码快的加载。

运行结果为

  1. FinalTest4 static block  
  2. 82 

下面的例子是讲,当子类被主动访问的时候,会引起其直接父类的初始化

  1. package com.bird.classLoad;  
  2.  
  3. class Parent{  
  4.       
  5.     static int a = 3;  
  6.       
  7.     static{  
  8.         System.out.println("Parent static block");  
  9.     }  
  10. }  
  11.  
  12. class Child extends Parent{  
  13.       
  14.     static int b = 4;  
  15.     static{  
  16.         System.out.println("Chind static block");  
  17.     }  
  18. }  
  19.  
  20. public class Test5 {  
  21.       
  22.     public static void main(String[] args) {  
  23.         System.out.println(Child.b);  
  24.           
  25.     }  
  26. }  

因为直接访问Child,b,会先初始化Parent类,然后初始化Child类。

运行结果为

  1. Parent static block  
  2. Chind static block  
  3. 4 

如果通过子类直接访问父类的变量,只会初始化父类而不会初始化子类

  1. package com.bird.classLoad;  
  2.  
  3. class Parent{  
  4.       
  5.     static int a = 3;  
  6.       
  7.     static{  
  8.         System.out.println("Parent static block");  
  9.     }  
  10. }  
  11.  
  12. class Child extends Parent{  
  13.       
  14.     static{  
  15.         System.out.println("Chind static block");  
  16.     }  
  17. }  
  18.  
  19. public class Test5 {  
  20.       
  21.     public static void main(String[] args) {  
  22.         System.out.println(Child.a);  
  23.           
  24.     }  
  25. }  

直接访问Parent类的a变量,则只会直接初始化parent类,不会初始化Child类

运行结果如下

  1. Parent static block
  2. 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值