即使使用子类型引用了静态字段,也仅初始化超类 [英] Only super class is initialized even though static field is referenced using sub type

查看:81
本文介绍了即使使用子类型引用了静态字段,也仅初始化超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对JAVA初始化过程进行一些研究. 这是一个很好的参考资料: 在JVM中加载和初始化类时

I am doing some research on JAVA initialization process. Here is a good material for reference: When a class is loaded and initialized in JVM

此页面上有规则说: 3)如果由于访问静态字段而触发了类初始化,则只有声明了静态字段的类才被初始化,即使子类的类型引用了静态字段,也不会触发超类或子类的初始化. ,子接口或按接口的实现类.

On this page there is rule says: 3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type of Sub Class, Sub Interface or by implementation class of interface.

我真的不明白这个主意.如果静态字段由Sub类引用,则此字段当然需要创建一个子类对象或由Sub类对象分配. 因此,它肯定会触发Sub类的初始化.

I really don't understand the idea. If the static field is referenced by Sub class, then this field of course need to create a sub class object or assigned by a Sub class object. So, it definitely triggers Sub class initialization.

我的解释出了什么问题?

What's wrong with my interpretation?

编辑:

  1. 它确实会触发超类静态初始化.
  2. 如果静态字段是final,并且在声明时初始化了static final字段.然后,它既不会加载类也不会初始化类,因为此static final字段是编译时常数值. 注意:如果static final字段在static块中初始化,则该语句不再成立.
  1. It DOES trigger Super Class static initialization.
  2. If the static field is final, and the static final field is initialized when declaring. Then it will neither load the class nor initialize the class, for this static final field is a compile time constant value. Attention: if the static final field is initialized in static block, then this statement does NOT hold anymore.

推荐答案

我认为关键是在这种情况下:

I think the point is that in a situation like this:

public class Superclass {
    public static long INIT_TIME = System.currentTimeMillis();

    static {
        System.out.println("Initializing Superclass");
    }
}

public class Subclass extends Superclass {
    static {
        System.out.println("Initializing Subclass");
    }
}

此代码:

long time = Subclass.INIT_TIME;

实际上被编译为:

long time = Superclass.INIT_TIME;

即使源代码引用了Subclass,也会打印

初始化超类".

and only "Initializing Superclass" will be printed, even though the source code referred to Subclass.

这篇关于即使使用子类型引用了静态字段,也仅初始化超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆