Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Polymorphism
What will be the output of this code?
class Parent {
  protected Number getValue() { return 10; }
}
class Child extends Parent {
  @Override
  public Integer getValue() { return 20; }
}
public class Test {
  public static void main(String[] args) {
    Parent p = new Child();
    System.out.println(p.getValue());
  }
}
A20
B10
CCompilation error due to return type
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Check method overriding rules

    Child overrides getValue() with covariant return type Integer (subtype of Number) and increased visibility (public).
  2. Step 2: Understand runtime method call

    Reference is Parent, object is Child, so Child's getValue() returns 20.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    Covariant return + dynamic dispatch = 20 [OK]
Quick Trick: Return type can be subtype; overridden method runs at runtime [OK]
Common Mistakes:
  • Expecting 10 from Parent method
  • Thinking return type mismatch causes error
  • Ignoring access modifier rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes