Java 类和静态 block

标签 java static

class Hello12 {
    static int b = 10;
    static {
        b = 100;
    }
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

在运行上面的代码时,输​​出为 100,因为当我调用 Hello 类时,首先执行静态 block ,将 b 的值设置为 100 并显示它。 但是当我写这段代码时:

class Hello12 {
    static {
         b = 100;
    }
    static int b = 10;
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

这里的输出是 10。我希望答案是 100,因为一旦执行了静态 block ,它就会给 b 的值是 100。所以在 main() 中,我调用了 Hello.b它应该提到 b (=100)。两个代码中的内存是怎么分配给b的?

最佳答案

在类的“详细初始化过程”中,Section 12.4.2 of the JLS状态:

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

这意味着好像第一个示例是:

b = 10;
b = 100;

第二个例子是:

b = 100;
b = 10;

最后一个作业“获胜”,解释你的输出。

关于Java 类和静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24895489/

相关文章:

arrays - Static 在声明字符数组时有什么用?

java - 如何将下划线转移到左侧?

java - 找不到 Robotium 存储库

java - Android - 从自定义ListView中删除项目

Java q关于类结构

c++ - C/C++ static const 局部变量的用途

Javascript - 从另一个静态方法访问静态方法抛出 ReferenceError

java - 日期返回 null

java - Java的时间序列数据库?

c++ - C++ 单例类实例的堆/动态与静态内存分配