← Quiz: Inheritance and Polymorphism: all 10 questions
Quiz: Inheritance and Polymorphism · Question 9 of 10
Animal a = new Animal(); Dog d = (Dog) a; What happens?
Animal a = new Animal(); Dog d = (Dog) a; What happens?
- A.a becomes a Dog
- B.ClassCastException at run time, because the object is not a Dog
- C.Compile error
- D.d is null
Answer & explanation
Correct answer: ClassCastException at run time, because the object is not a Dog
The compiler allows the cast because an Animal variable might hold a Dog, but the real object is a plain Animal. Check with instanceof first.
Can you get the rest right without peeking?
Take the timed Quiz: Inheritance and Polymorphism quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →