OCP Java SE 6 练习题 - WeatherTest 枚举

OCP Java SE 6 Practice Questions - WeatherTest Enum

"OCP Java SE 6 Programmer Practice Exams (Exam 310-065)" 评估测试 2 中的一个问题。

鉴于:

public class WeatherTest {
static Weather w;

public static void main(String[] args) {
    System.out.print(w.RAINY.count + " " + w.Sunny.count + " ");
}

enum Weather {
    RAINY, Sunny;
    int count = 0;

    Weather() {
        System.out.print("c ");
        count++;
    }
}
}

What is the result?

A. c 1 c 1

B. c 1 c 2

C. c c 1 1

D. c c 1 2

E. c c 2 2

F. Compilation fails.

G. An exception is thrown at runtime.

书上的答案是C

但是当我尝试 运行 这段代码时,出现编译错误,显示 "The static field WeatherTest.Weather.RAINY should be accessed in a static way"。

哪个是正确的和预期的,但是没有人在互联网上抱怨它,所以我想知道我是否遗漏了什么?跟Java版本有关系吗?

书上说的对,正确答案是C,c c 1 1可考here

此错误是由您的 IDE 产生的,它是从警告中升级而来的。假设您正确复制粘贴了所有代码。准备考试时不要使用 IDE,使用最简单的文本编辑器和 javac.

它与Java版本无关,它在Java SE 6 及更高版本的所有版本中都是一样的。

最后但并非最不重要的一点 - 永远不要编写那样的代码。这只是考试 hokus-pokus...

代码编译并给出答案 C。

所有发生的事情是您的 IDE 向您发出警告,您不应访问 class 实例上的静态成员,因为它会造成混淆。 w.RAINY 使它看起来像 RAINY 是一个实例字段,而实际上它是静态的。在这种情况下 w 实际上是 null。访问静态成员的常用方法是使用ClassName.member。这里应该写Weather.RAINY.