Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Java - Polymorphism
Identify the error in this code snippet:
class Animal {} class Dog extends Animal {} public class Test { public static void main(String[] args) { Animal a = new Animal(); Dog d = (Dog) a; } }
ANo error, code runs fine
BCompilation error due to invalid cast
CRuntime ClassCastException occurs
DDog cannot extend Animal
Step-by-Step Solution
Solution:
  1. Step 1: Analyze casting from superclass instance

    'a' refers to an Animal object, not a Dog instance.
  2. Step 2: Understand runtime casting rules

    Downcasting Animal to Dog compiles but causes ClassCastException at runtime.
  3. Final Answer:

    Runtime ClassCastException occurs -> Option C
  4. Quick Check:

    Downcasting superclass instance to subclass causes runtime error [OK]
Quick Trick: Downcast superclass instance to subclass causes runtime error [OK]
Common Mistakes:
  • Expecting compile-time error instead of runtime error
  • Assuming cast changes actual object type
  • Ignoring need to check object type before downcast

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes