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.


Why can't you upcast a List<Apple> to a List<Fruit>?

  1. Because the List types are invariant

  2. Because a Fruit is not an Apple

  3. Because of runtime type information

  4. Because generics do not support covariance by default

The correct answer is: Because generics do not support covariance by default

Upcasting is the process of converting an object of a subtype to its supertype. It is usually allowed when working with inheritance, but it is not possible with generic types by default. This is because generics are invariant in Java, meaning that subtypes cannot be used in place of their supertype. So, even though an Apple is a subtype of Fruit, a List<Apple> cannot be used as a List<Fruit>. This is because it would violate type safety as the List<Fruit> could end up containing other types of Fruit that are not Apples. Therefore, options A, B, and C are incorrect because they do not address the specific reason why upcasting a List<Apple> to a List<Fruit> is not allowed in Java.