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.


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.