Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q4 of 15
Java - Polymorphism
What will be the output of this Java code?
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
AAnimal sound
BRuntime error
CCompilation error
DBark
Step-by-Step Solution
Solution:
  1. Step 1: Understand object type and method call

    Variable 'a' is declared as Animal but refers to a Dog object. Method sound() is overridden in Dog.
  2. Step 2: Determine which method runs

    At runtime, Java calls Dog's sound() because of polymorphism (dynamic method dispatch).
  3. Final Answer:

    Bark -> Option D
  4. Quick Check:

    Polymorphism calls subclass method at runtime [OK]
Quick Trick: Reference type can be parent, object type decides method [OK]
Common Mistakes:
  • Expecting superclass method to run
  • Confusing compile-time and runtime method binding
  • Thinking this causes errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes