Bird
0
0

What will happen when this code runs?

medium📝 Predict Output Q5 of 15
Java - Polymorphism
What will happen when this code runs?
class Animal {} class Dog extends Animal {} class Cat extends Animal {} public class Test { public static void main(String[] args) { Animal a = new Dog(); Cat c = (Cat) a; } }
ACompilation error due to invalid cast
BProgram runs without error
CRuntime ClassCastException
DDog object converted to Cat object
Step-by-Step Solution
Solution:
  1. Step 1: Understand object and reference types

    'a' refers to a Dog object but is cast to Cat, which is unrelated subclass.
  2. Step 2: Identify runtime behavior

    At runtime, JVM detects invalid cast and throws ClassCastException.
  3. Final Answer:

    Runtime ClassCastException -> Option C
  4. Quick Check:

    Invalid downcast causes runtime ClassCastException [OK]
Quick Trick: Invalid downcast throws ClassCastException at runtime [OK]
Common Mistakes:
  • Expecting compile-time error instead of runtime error
  • Assuming cast silently converts object type
  • Thinking program runs without error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes