gpt4 book ai didi

java - Java 中静态和非静态前向引用的内部工作

转载 作者:搜寻专家 更新时间:2023-11-01 03:16:37 26 4
gpt4 key购买 nike

我正在使用 Java 中的前向引用,想知道为什么 Java 允许使用 ClassName(在静态变量中)或使用 this 引用(在实例变量的情况下)进行前向引用? 在 JVM 级别发生的后台进程是什么?例如:

静态前向引用-

class StaticForwardReferences {
static {
sf1 = 10; // (1)
int b = sf1 = 20; // (2)
int c = StaticForwardReferences.sf1; // (3) Works fine
// Above statement allows the allocation of value of 'sf1'
// to variable 'c' just because it is accessed with class name
// instead of direct name

// whereas below statement throws illegal forward reference
// error at compile time
System.out.println(sf1); // (4) Illegal forward reference
}
static int sf1 = sf2 = 30;
static int sf2;

public static void main(String[] args) {}
}

如果我们打印变量的值 c,它显示最近分配给 sf1 的值。

非静态前向引用-

class NonStaticForwardReferences {
{
nsf1 = 10;
System.out.println(this.nsf1); // 10
nsf1 = sf1;
// System.out.println(nsf1); Illegal forward reference
int b = nsf1 = 20;

int c = this.nsf1;
System.out.println(c); // 20
// why variable 'c' is initialized to 20 when used with 'this' reference
// instead of showing illegal forward reference, how it works in the background?
}

int nsf1 = nsf2 = 30;
int nsf2;
static int sf1 = 5;

public static void main(String[] args) {}
}

请阐明上述两种情况在幕后发生的后台进程。提前致谢! :)

最佳答案

JLS, Section 8.3.3 , 说明了对静态变量(“类变量”)进行前向引用的条件是编译器错误,尽管它没有说明原因。

Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope (§6.3). Specifically, it is a compile-time error if all of the following are true:

  • The declaration of a class variable in a class or interface C appears textually after a use of the class variable;

  • The use is a simple name in either a class variable initializer of C or a static initializer of C;

  • The use is not on the left hand side of an assignment;

  • C is the innermost class or interface enclosing the use.

(斜体 强调我的)

出现实例变量前向引用错误的情况类似:

Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. Specifically, it is a compile-time error if all of the following are true:

  • The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;

  • The use is a simple name in either an instance variable initializer of C or an instance initializer of C;

  • The use is not on the left hand side of an assignment;

  • C is the innermost class or interface enclosing the use.

(斜体 强调我的)

在这两种情况下,使用简单名称 是这里的关键条件。这意味着使用不带任何限定符(如 this 或类名)的变量。这就是 this.nsf1NonStaticForwardReferences 中工作的原因。如果删除 this,则会发生错误。这也是sf1有错误而StaticForwardReferences.sf1;没有错误的原因。

关于java - Java 中静态和非静态前向引用的内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48065649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com