Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Inheritance

What will be the output of the following code?

class Parent {
    void greet() { System.out.println("Hello from Parent"); }
}
class Child extends Parent {
    @Override
    void greet() { System.out.println("Hello from Child"); }
}
public class Test {
    public static void main(String[] args) {
        Parent obj = new Child();
        obj.greet();
    }
}
AHello from Parent
BCompilation error
CRuntime error
DHello from Child
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic method dispatch

    When a parent reference points to a child object, overridden methods in child are called at runtime.
  2. Step 2: Trace the method call

    obj is Parent type but refers to Child instance. Calling greet() runs Child's version.
  3. Final Answer:

    Hello from Child -> Option D
  4. Quick Check:

    Parent ref + Child object calls Child method [OK]
Quick Trick: Parent reference calls child's overridden method at runtime [OK]
Common Mistakes:
  • Expecting parent method output
  • Confusing compile-time and runtime method binding
  • Thinking method overloading applies here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes