为什么静态初始化程序块在这种简单的情况下不运行? [英] Why static initializer block not run in this simple case?

查看:152
本文介绍了为什么静态初始化程序块在这种简单的情况下不运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 class Z
{
    static final int x=10;
    static
    {
        System.out.println("SIB");
    }

}
public class Y
{
    public static void main(String[] args)
    {
        System.out.println(Z.x);
    }
}

输出:10
为什么静态初始化块在这种情况下不加载?当静态x调用时,所有类z的静态成员必须至少加载一次但静态初始化块不加载。

Output :10 why static initialization block not load in this case?? when static x call so all the static member of class z must be load at least once but static initialization block not loading.

推荐答案


在声明中包含静态修饰符的字段称为
静态字段类变量它们与类相关联,
而不是任何对象。该类的每个实例共享一个
类变量,该变量位于内存中的一个固定位置。
任何对象
都可以更改类变量的值,但类变量也可以
在不创建类实例的情况下进行操作

Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class

因此,当您调用 Zx 如下所示:

So, when you call Z.x as below:

System.out.println(Z.x);

它不会初始化类,除非你调用 Zx 它将从该固定内存位置获得 x

It won't initialize the class, except when you call that Z.x it will get that x from that fixed memory location.

当JVM加载类Z 时,会运行静态块。这里永远不会加载,因为它可以直接访问 x 而无需加载类。

Static block is runs when JVM loads class Z. Which is never get loaded here because it can access that x from directly without loading the class.

这篇关于为什么静态初始化程序块在这种简单的情况下不运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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