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

               

当一个类中有声明为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 block82

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

package com.bird.classLoad;class Parent{  static int a = 3;  static{  System.out.println("Parent static block"); }}class Child extends Parent{  static int b = 4static{  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 blockChind static block4

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

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 block3


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值