Given the following enum declaration, how many lines contain compilation errors?
package mypkg;/*from w w w .ja v a 2s.c o m*/ public enum Answer { TRUE(-10) { @Override String getName() { return "RIGHT"; }}, FALSE(-10) { public String getName() { return "WRONG"; }}, UNKNOWN(0) { @Override public String getName() { return "LOST"; }} private final int value; Answer(int value) { this.value = value; } public int getValue() { return this.value; } protected abstract String getName(); }
C.
The code does not compile since it contains two compilation errors, making Option A incorrect.
The enum list is not terminated with a semicolon (;).
A semicolon (;) is required anytime an enum includes anything beyond just the list of values, such as a constructor or method.
Second, the access modifier of TRUE's implementation of getName()
is package-private, but the abstract method signature has a protected modifier.
Since package-private is a more restrictive access than protected, the override is invalid and the code does not compile.
For these two reasons, Option C is the correct answer.
Note that the @Override annotation is optional in the method signature, therefore FALSE's version of getName()
compiles without issue.
The Answer constructor does not include a private access modifier, but the constructor compiles without issue.
Enum constructors are assumed to be private if no access modifier is specified, unlike regular classes where package-private is assumed if no access modifier is specified.