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

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

Prepare for your Java exam with our ultimate quiz based on 'Thinking in Java'. Engage with expertly crafted questions that enhance your learning process. Perfect for Java enthusiasts looking to solidify their knowledge!

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.


Under what circumstance is it safe to cast an object from a List<? extends Fruit>?

  1. When casting to Fruit or any of its subclasses

  2. Only when casting to an Apple

  3. When you are certain of the list's element types

  4. It is never safe to cast objects from such a list

The correct answer is: When you are certain of the list's element types

When casting an object from a List<? extends Fruit>, the only safe circumstance is when you are completely certain of the list's element types. This means that you know, without a doubt, that all elements in the list are of a specific subtype of the Fruit class. Option A is incorrect because simply casting to Fruit or any of its subclasses is not always safe. Option B is incorrect because relying on the fact that the list can only contain Apples is not a guarantee of safety. Option D is incorrect because there are some situations where it is safe to cast from such a list, as in the case of being certain of the element types.