静态变量初始化顺序,Java [英] Order of static variable initialization, Java
问题描述
可能的重复:
Java 静态类初始化
静态块的顺序和类中执行的静态变量?
当我运行这段代码时,答案是 1,我以为是 2.每一步的初始化顺序和k的值是什么?
When I run this code the answer is 1, I thought it would be 2. What is the order of initialization and the value of k in each step?
public class Test {
static {k = 2;}
static int k = 1;
public static void main(String[] args) {
System.out.println(k);
}
}
编辑 1:作为k 设置为默认值"的后续内容,为什么下一段代码无法编译?出现错误在定义字段之前无法引用字段".
Edit 1: As a follow up to "k is set to default value" then why this next code doesn't compile? Theres an error "Cannot reference a field before it's defined".
public class Test {
static {System.out.println(k);}
static int k=1;
public static void main(String[] args) {
System.out.println(k);
}
}
编辑 2:由于某些我不知道的原因,它 ^ 在而不是k"它的Test.k"时起作用.
Edit 2: For some unknow to me reason it^ works when instead of "k" its "Test.k".
谢谢大家的回答.这就足够了:D
Thanks for all the answers. this will sufice :D
推荐答案
它们按照您编写它们的顺序执行.如果代码是:
They are executed in the order that you write them. If the code is:
public class Test {
static int k = 1;
static {k = 2;}
public static void main(String[] args) {
System.out.println(k);
}
}
那么输出变为2.
初始化的顺序是:..the类变量初始化器和类的静态初始化器...,按文本顺序,就好像它们是一个单独的块.
值(对于您的代码)是:k = 0(默认),然后设置为 2,然后设置回 1.
And the values (for your code) are: k = 0 (default), then it's set to 2, then it's set back to 1.
您可以通过运行以下代码来检查它是否实际设置为 2:
You can check that it's actually set to 2 by running the following code:
private static class Test {
static {
System.out.println(Test.k);
k = 2;
System.out.println(Test.k);
}
static int k = 1;
public static void main(String[] args) {
System.out.println(k);
}
}
这篇关于静态变量初始化顺序,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!