我用的是同一种概念,我在头等舱用过。
b 被初始化为 0,我在使用 b 的所有地方都得到 0。
一段时间后,我找到了原因并运行调试器,发现 a 在函数调用之前没有分配任何值。变量 a 只有值默认值 0。
但是当我运行类 Test2 时。它给出了输出 5。
我想知道这个初始化是什么时候发生的? 我知道静态变量在编译时获得值(value)。但是静态最终呢? 这个变量什么时候得到它的值?
public class Test1 {
static int b=add();
static int add()
{
return a;
}
static int a=5;
public static void main(String[] args) {
System.out.println(b);
}
}
//Gives output 0
public class Test2 {
static int b=add();
static int add()
{
return a;
}
final static int a=5;
public static void main(String[] args) {
System.out.println(b);
}
}
//gives output 5
最佳答案
来自 12.4.2 部分在Java Language Specifications中,初始化Class的过程如下:
- Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
- 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.
因此最终变量将在静态变量之前被初始化。你将得到输出 5
。
关于java - 静态和最终静态赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364806/