A question in "OCP Java SE 6 Programmer Practice Exams (Exam 310-065)" Assesment test 2.
Given:
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.
The answer the book says C.
But when I try running this code I get compilation error, saying "The static field WeatherTest.Weather.RAINY should be accessed in a static way".
Which is correct and expected, but no one has complained about it on internet, so I am wondering if I am missing something? Has it got something to do with Java version or something?
The code compiles and gives answer C.
All that is happening is that your IDE is issuing you with a warning that you should not access static members on an instance of a class, as it it confusing. w.RAINY
makes it look like RAINY
is an instance field, when in fact it is static. In this case w
is actually null
. The usual way to access static members is to use ClassName.member
. Here you should write Weather.RAINY
.