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

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

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

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.