Bird
0
0

Consider this code:

hard📝 Application Q15 of 15
Java - Polymorphism
Consider this code:
class Animal {
    Number getValue() { return 10; }
}
class Dog extends Animal {
    @Override
    Integer getValue() { return 20; }
}

Which statement about this overriding is correct?
AThis is valid because Integer is a subclass of Number (covariant return type).
BThis causes a compile-time error due to different return types.
CThis is invalid because return types must be exactly the same.
DThis is invalid because @Override cannot be used with different return types.
Step-by-Step Solution
Solution:
  1. Step 1: Check return types in parent and child methods

    Parent returns Number, child returns Integer, which is a subclass of Number.
  2. Step 2: Understand covariant return types in Java overriding

    Java allows child methods to return a subtype of the parent's return type when overriding.
  3. Final Answer:

    This is valid because Integer is a subclass of Number (covariant return type). -> Option A
  4. Quick Check:

    Covariant return types allowed = A [OK]
Quick Trick: Child can return subtype of parent's return type when overriding [OK]
Common Mistakes:
  • Thinking return types must be exactly the same
  • Assuming @Override forbids different return types
  • Confusing overloading with overriding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes