Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Polymorphism
What will be the output of the following Java code?
class Animal {
  void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
  void sound() { System.out.println("Dog barks"); }
}
public class Test {
  public static void main(String[] args) {
    Animal a = new Dog();
    a.sound();
  }
}
AAnimal sound
BCompilation error
CDog barks
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Identify polymorphic call

    Variable 'a' is of type Animal but refers to a Dog object.
  2. Step 2: Determine method execution

    At runtime, Dog's overridden sound() method is called, printing "Dog barks".
  3. Final Answer:

    Dog barks -> Option C
  4. Quick Check:

    Overridden method runs based on object type [OK]
Quick Trick: Method called depends on actual object, not reference type [OK]
Common Mistakes:
  • Expecting superclass method output
  • Confusing compile-time and runtime method binding
  • Thinking code causes errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes