OCP Question 53, Explanation

Given:

public enum Season {
    WINTER (6),
    SPRING(10),
    SUMMER (25),
    FALL(14);
    private int averageTemp;
    public Season(int averageTemp) {
        this.averageTemp = averageTemp;
    }
    public int getTemp() {return averageTemp;}
}
public class Vacationer {
    public static void main (String[] args) {
        Season ssn = new Season.SUMMER;
        System.out.println(ssn.getTemp());
    }
}

Which two modifications enable the given code to compile?

A. Nest the Season enumeration declaration within the Vacationer class.
B. Make the Season enumeration constructor private.
C. Remove the new keyword from the instantion of ssn.

D. Make the getter method of averageTemp as a static method.
E. Add the final keyword in the declaration of averageTemp.

 

The correct answer is BC.

 

When it comes to enumerations on 1Z0-809, it is sufficient to remember just one thing: enums’ constructors are implicitly private, therefore, any other access modifier is unacceptable; everything else will follow automatically.

Take, for example, our current Problem: as soon as we apply the above rule, it becomes evident that option B is in, and since we may not call Season’s ctor outside the enum itself, the new keyword in main() must be removed, as well. As a matter of fact, an enum instance is created fully automatically when any enum constant is first called.

Alternative approach to deal with enumerations on our exam: as Joshua Block once put it, enums are examples of perfectly implemented Singleton Pattern.

Leave Comment

Your email address will not be published.