Difficulty: Easy
Correct Answer: Compilation fails.
Explanation:
Introduction / Context: Java supports covariant return types: an overriding method may return a subtype of the original return type. This item checks whether changing a return type from Integer to Long in a subclass is legal.
Given Data / Assumptions:
Concept / Approach: For an override to be valid, the subclass method’s return type must be the same or a subtype of the superclass method’s return type. Since Long is not a subtype of Integer, the method in Sub does not correctly override; it conflicts and causes a compile-time error about attempting to use an incompatible return type.
Step-by-Step Solution:
Check superclass signature: Integer getLength().Check subclass signature: Long getLength().Determine type relationship: Long !<: Integer.Compiler reports error: return type is incompatible with Super.getLength().Verification / Alternative check: If Super returned Number, Sub could validly return Integer or Long. Alternatively, change both to int/Integer consistently.
Why Other Options Are Wrong:
Common Pitfalls: Misunderstanding covariance as permitting any related types; it must be a subtype relationship in the same hierarchy.
Final Answer: Compilation fails.
Discussion & Comments