静态变量在声明之前如何访问?
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
}
}
为什么我可以在课堂上使用 y,但不能直接使用?
y 是什么时候定义的?
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?
When is y defined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
§8.3.2.3:
The precise rules governing forward reference to class variables are described in the section §8.3.2.3 of the JLS:
我假设通过使用该类,编译器将推迟查找变量,直到该类完成,因此它找到 y,但如果您只是像注释一样定义它,则它尚未定义,因此会失败
I would assume that by using the class, the compiler would defer looking for the variable until the class was complete, so it finds y, but if you just define it like the comment it is not yet defined so it fails
静态变量在类加载期间按照类中声明的顺序定义。当 JVM 加载
Main
类时,将定义x
,然后定义y
。这就是为什么你在初始化x
时不能直接使用y
,你创建了一个叫做前向引用的东西,你引用了一个当前不是的变量定义了,这对于编译器来说是非法的。当使用
Main.y
时,我认为会发生以下情况:Main
,x
初始化被调用x 等于
Main.y
,编译器会看到对类的引用,因此它将结束将x
定义为成员y 的当前值类
。它将这种情况视为Main
的Main
是一个不同的类。请注意,在本例中,初始化
x
时,y
暂时尚未定义。因此,x
的值为0
。Static variables are defined in order of declaration in the class, during class loading. When the JVM will load the
Main
class,x
will be defined, theny
. That's why you can't directly usey
when initializingx
, you create something that's called a forward reference, you refers to a variable not currently defined, and that's illegal for the compiler.When using
Main.y
, I think the following happens:Main
,x
initialization is calledx
to be equals toMain.y
, the compiler sees a reference to a class, so it will end definingx
to the current value of the membery
of the classMain
. It treats this case as ifMain
was a different class.Note that in this case, when initializing
x
,y
hasn't be defined for the moment. Sox
will have a value of0
.你不被允许这样做,因为它毫无意义。唯一可能的解释是 y 被初始化为零,并且您已经有两种表达方式。你不需要这个。
You're not permitted to do it because it is meaningless. The only possible interpretation is that y is initialized to zero, and you already have two ways of saying that. You don't need this.
也许编译器在创建静态变量时会使用堆栈中的类创建具有默认值的静态变量的引用,然后分配提供的值。
Perhaps the compiler creates the references of the static variables with default values with the class in the stack, when it's created and then assigns the provided values.