Bird
0
0

Examine the code below and identify the issue:

medium📝 Debug Q7 of 15
Java - Polymorphism
Examine the code below and identify the issue:
class Bird { void fly() { System.out.println("Flying"); } }
class Sparrow extends Bird { void chirp() { System.out.println("Chirp"); } }
public class Test {
public static void main(String[] args) {
Bird b = new Bird();
Sparrow s = (Sparrow) b;
s.chirp();
}
}
AClassCastException at runtime due to invalid downcast
BCompilation error because chirp() is undefined in Bird
CNo error; prints "Chirp"
DNo error; prints "Flying"
Step-by-Step Solution
Solution:
  1. Step 1: Analyze object creation

    Variable b references a Bird object, not a Sparrow.
  2. Step 2: Downcasting issue

    Downcasting b to Sparrow is invalid at runtime, causing ClassCastException.
  3. Step 3: Method call

    Calling chirp() on invalid casted object triggers exception.
  4. Final Answer:

    ClassCastException at runtime due to invalid downcast -> Option A
  5. Quick Check:

    Downcast only safe if object is instance of subclass [OK]
Quick Trick: Downcast only safe if object is subclass instance [OK]
Common Mistakes:
  • Assuming downcast always safe
  • Ignoring runtime exceptions
  • Confusing compile-time and runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes