【发布时间】:2014-07-22 18:56:20
【问题描述】:
class Hello12 {
static int b = 10;
static {
b = 100;
}
}
class sample {
public static void main(String args[]) {
System.out.println(Hello12.b);
}
}
在运行上面的代码时,输出为 100,因为当我调用 Hello 类时,首先执行静态块,将 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,因为一旦执行了静态块,它给 b 的值为 100。所以在 main() 中,我调用了 Hello.b它应该提到 b (=100)。两个代码中的内存是怎么分配给b的?
【问题讨论】:
-
+1。在实践中,使用
final。