gpt4 book ai didi

java - 在 Java 中访问内部类中的静态最终字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:37 25 4
gpt4 key购买 nike

当我尝试编译以下代码时,出现编译错误:

unexpected type System.out.println( new Test().C.i );
^
required: class,package
found: value

class Test {

class C {
static final int i = 0;
}

public static void main(String... z) {
System.out.println( new Test().C.i );
}

}

但是,如果我将 new Test().C.i 更改为 new Test().new C().i,它编译得很好。

为什么?如果我在 C 中是静态的,那么我就不必实例化 C。我应该能够通过类 C 调用它,而不是 C 对象。

我错过了什么?

最佳答案

问题是 "."Java 语法中的标识符 期望标识符引用变量而不是类型。

这在 6.5.6.2 中指定。 JLS 的限定表达式名称(以及其他地方):

If Q is a type name that names a class type (§8 (Classes)), then:

If there is not exactly one accessible (§6.6) member of the class type that is a field named Id, then a compile-time error occurs.

Otherwise, if the single accessible member field is not a class variable (that is, it is not declared static), then a compile-time error occurs.

Otherwise, if the class variable is declared final, then Q.Id denotes the value of the class variable.

The type of the expression Q.Id is the declared type of the class variable after capture conversion (§5.1.10).

If Q.Id appears in a context that requires a variable and not a value, then a compile-time error occurs.

Otherwise, Q.Id denotes the class variable.

The type of the expression Q.Id is the declared type of the class variable after capture conversion (§5.1.10).

Note that this clause covers the use of enum constants (§8.9), since these always have a corresponding final class variable.

虽然我完全理解为什么您认为它会像那样工作的逻辑 - 我实际上希望它也能工作 - 这没什么大不了的:因为总是只有一个 i 你可以通过Test.C.i 来引用它。如果 i 是非静态的,new Test().new C().i 将是访问它的正确方法。

另一种查看方式是阅读 15.8. Primary Expressions它具有主要表达式的实际语法(这是我们在这里处理的内容):它允许 ClassInstanceCreationExpression(这就是为什么 new Test().new C().i有效)以及 FieldAccess(适用于 Test.C.i,因为“类”是递归解析的 - 只有最后一个标识符必须引用一个字段)。

关于java - 在 Java 中访问内部类中的静态最终字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673092/

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