Java静态变量 [英] Java Static variables
问题描述
public class Main {
static int x = Main.y;
// static int x = y; //Not allowed; y is not defined
static int y = x;
public static void main(String[] args) {
System.out.println(x);//prints 0
}
}
为什么我被允许在课堂上使用,但不能直接使用?
How come I am allowed to use y trough the class, but not directly?
何时定义?
推荐答案
8.3.2.3初始化期间使用字段的限制
成员的声明需要只有当成员是
类的实例
(分别为static
)字段时,
才会在使用
之前以文本方式显示或接口C和所有
以下条件成立:
8.3.2.3 Restrictions on the use of Fields during Initialization
The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively
static
) field of a class or interface C and all of the following conditions hold:
- 用法发生在一个实例中(分别为
静态
)变量
初始值为C或实例
(分别为静态
)初始值为
C。 - 用法不在作业的左侧。
- 用法是通过一个简单的名称。
- C是封闭用法的最内层类或接口。
- The usage occurs in an instance (respectively
static
) variable initializer of C or in an instance (respectivelystatic
) initializer of C. - The usage is not on the left hand side of an assignment.
- The usage is via a simple name.
- C is the innermost class or interface enclosing the usage.
如果上述四项要求中的任何
不符合
,则会发生编译时错误。
A compile-time error occurs if any of the four requirements above are not met.
这意味着编译时错误
来自测试程序:
This means that a compile-time error results from the test program:
class Test {
int i = j; // compile-time error: incorrect forward reference
int j = 1;
}
而以下示例编译
且没有错误:
whereas the following example compiles without error:
class Test {
Test() { k = 2; }
int j = 1;
int i = j;
int k;
}
即使构造函数
(§8.8)测试是指
字段k是声明三行
稍后。
even though the constructor (§8.8) for Test refers to the field k that is declared three lines later.
这些限制设计为
catch,在编译时,循环或
,否则初始化错误。
因此,两者:
These restrictions are designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:
class Z {
static int i = j + 2;
static int j = 4;
}
和:
class Z {
static { i = j + 2; }
static int i, j;
static { j = 4; }
}
导致编译时错误。
方法的访问不以
方式检查,因此:
result in compile-time errors. Accesses by methods are not checked in this way, so:
class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
产生输出:
0
因为变量i
的初始化程序使用类方法peek在变量
初始化程序初始化j
之前访问变量j的值
,此时它仍然是
的默认值为(§4.12.5)。
这篇关于Java静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!