Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q4 of 15
Java - Inheritance
What will be the output of this Java code?
class Parent {
  void greet() { System.out.println("Hello from Parent"); }
}
class Child extends Parent {
  void greet() { System.out.println("Hello from Child"); }
}
public class Test {
  public static void main(String[] args) {
    Parent p = new Child();
    p.greet();
  }
}
AHello from Parent
BRuntime error
CCompilation error
DHello from Child
Step-by-Step Solution
Solution:
  1. Step 1: Understand method overriding and polymorphism

    When a child class overrides a method, the child's version runs even if the reference is of parent type.
  2. Step 2: Analyze the code execution

    Variable p is of type Parent but refers to Child object, so Child's greet() runs.
  3. Final Answer:

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

    Overridden method runs from Child class [OK]
Quick Trick: Overridden methods run from actual object type [OK]
Common Mistakes:
  • Thinking parent method runs due to reference type
  • Expecting compilation or runtime errors
  • Ignoring method overriding rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes