Java method overriding and covariant returns: can a subclass change Integer to Long in an override?\n\nclass Super {\n public Integer getLength() { return new Integer(4); }\n}\npublic class Sub extends Super {\n public Long getLength() { return new Long(5); }\n public static void main(String[] args) {\n Super sooper = new Super();\n Sub sub = new Sub();\n System.out.println(sooper.getLength().toString() + "," + sub.getLength().toString());\n }\n}

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:

  • Super.getLength() returns Integer.
  • Sub.getLength() attempts to return Long.
  • Integer and Long are unrelated sibling classes; neither is a subtype of the other.


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:

  • Any printed output assumes successful compilation.


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

No comments yet. Be the first to comment!
Join Discussion