Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Want to excel in Java? Test your knowledge with our ultimate quiz based on 'Thinking in Java'. Engage with multiple-choice questions and in-depth explanations. Boost your understanding and prepare for your exam with confidence.

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


How can you get enum instances if 'values()' is not available due to upcasting?

  1. Using 'getEnumConstants()' method

  2. With reflection

  3. Cannot get instances

  4. Using 'valueOf()' method

The correct answer is: Using 'getEnumConstants()' method

After upcasting, the enum class is seen as a normal class, therefore the 'values()' method is no longer available. An alternative method to get the enum instances is by using the 'getEnumConstants()' method, which will return an array of all the enum instances. Option B, using reflection, is incorrect because it is not efficient and can only obtain the enum values one by one. Option C is also incorrect because, as mentioned before, the 'getEnumConstants()' method can return the enum instances. Option D, using 'valueOf()' method, is incorrect because this method only takes in a string parameter and returns an enum constant, not all the enum instances. Therefore, the correct answer is A.