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/