静态变量初始化的顺序,Java [英] Order of static variable initialization, Java
问题描述
可能重复:
Java静态类初始化
以什么顺序执行的类中的静态块和静态变量?
当我运行此代码时答案是1,我认为它将是2.
初始化的顺序和每一步中k的值是什么?
public class Test {
static {k = 2;}
static int k = 1;
public static void main(String [] args){
System.out.println(k);
}
}
编辑1:作为后续k是设置为默认值那么为什么下一个代码不能编译?这是一个错误在定义之前无法引用字段。
公共类测试{
静态{System.out.println(k);}
static int k = 1;
public static void main(String [] args){
System.out.println(k);
}
}
编辑2:对于一些我不知道的原因^当代替k而不是Test.k时有效。
感谢所有答案。这将是足够的:D
它们按照您编写它们的顺序执行。如果代码是:
public class Test {
static int k = 1;
static {k = 2;}
public static void main(String [] args){
System.out.println(k);
}
}
然后输出变为2. / p>
初始化的顺序是: ..类的类变量初始值设定项和静态初始值设定项...,按文本顺序排列,好像它们是一个块一样。
值(对于你的代码)是:k = 0(默认值),然后它被设置为2,然后它被设置回1.
您可以通过运行以下代码来检查它实际设置为2:
私有静态类测试{
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);
}
}
Possible Duplicate:
Java static class initialization
in what order are static blocks and static variables in a class executed?
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);
}
}
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);
}
}
Edit 2: For some unknow to me reason it^ works when instead of "k" its "Test.k".
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);
}
}
then the output becomes 2.
The order of initialization is: ..the class variable initializers and static initializers of the class..., in textual order, as though they were a single block.
And the values (for your code) are: k = 0 (default), then it's set to 2, then it's set back to 1.
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屋!