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

Dive into the depths of Java with our quiz based on "Thinking in Java, Fourth Edition" by Bruce Eckel. Test your knowledge, solidify concepts, and prepare for certification with challenging questions and insightful feedback.

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 cannot be used as a List. This is because it would violate type safety as the List 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 to a List is not allowed in Java.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy