1Z0-809 practice question 20 of 25

Given: public enum USCurrency { PENNY (1), NICKLE(5), DIME (10), QUARTER(25); private int value; public USCurrency(int value) { this.value = value; }…

Full set: 196 questions
Given: public enum USCurrency { PENNY (1), NICKLE(5), DIME (10), QUARTER(25); private int value; public USCurrency(int value) { this.value = value; } public int getValue() {return value;} } public class Coin { public static void main (String[] args) { USCurrency usCoin =new USCurrency.DIME; System.out.println(usCoin.getValue()): } } Which two modifications enable the given code to compile? (Choose two.)
Answer options
A: Nest the USCurrency enumeration declaration within the Coin class.
B: Make the USCurrency enumeration constructor private. Correct answer
C: Remove the new keyword from the instantion of usCoin. Correct answer
D: Make the getter method of value as a static method.
E: Add the final keyword in the declaration of value.
Correct Answer:
B. Make the USCurrency enumeration constructor private.; C. Remove the new keyword from the instantion of usCoin.
Explanation

There are two compilation errors in the provided code. First, enum constructors cannot be declared public or protected; they are implicitly private. The public modifier on the USCurrency constructor must be removed or changed to private. Second, enum constants are static, final instances and are not created using the new keyword. The line new USCurrency.DIME is incorrect syntax for accessing an enum constant. It must be changed to USCurrency.DIME. Therefore, making the constructor private and removing the new keyword will allow the code to compile.

Why Incorrect

A. Nesting the enum is a stylistic choice and is not required for the code to compile. A top-level enum is perfectly valid.
D. The getValue() method is an instance method that correctly retrieves the value for a specific enum constant (e.g., DIME). Making it static would be incorrect.
E. While making the value field final is good practice, it is not required for the code to compile.

References

1. Oracle, The Java™ Language Specification, Java SE 8 Edition. Section 8.9, "Enums". It states, "An enum constant is implicitly static and final."

2. Oracle, The Java™ Language Specification, Java SE 8 Edition. Section 8.9.2, "Enum Body and Member Declarations". It specifies, "It is a compile-time error if the constructor of an enum type is declared public or protected."

3. Oracle, The Java™ Tutorials. "Enum Types". docs.oracle.com/javase/tutorial/java/javaOO/enum.html. This tutorial shows the correct syntax for declaring and using enums, including accessing constants without the new keyword.

Scroll to Top