Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Polymorphism
What will be the output of this code?
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } void fetch() { System.out.println("Dog fetches"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); ((Dog) a).fetch(); } }
AAnimal sound\nDog fetches
BDog barks\nDog fetches
CDog barks\nAnimal sound
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method calls on upcasted object

    Variable 'a' is of type Animal but refers to Dog object. Calling a.sound() calls Dog's overridden method.
  2. Step 2: Downcast to call subclass method

    Downcasting 'a' to Dog allows calling fetch(), which prints "Dog fetches".
  3. Final Answer:

    Dog barks\nDog fetches -> Option B
  4. Quick Check:

    Upcast calls overridden method, downcast calls subclass method [OK]
Quick Trick: Upcast calls subclass override; downcast accesses subclass-only methods [OK]
Common Mistakes:
  • Expecting superclass method output for sound()
  • Forgetting to downcast before calling fetch()
  • Assuming compilation error due to casting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes