Java SE 8 Programmer I — Question 193

Given the class definitions:
class C1 {}
class C2 extends C1 {}
class C3 extends C2 {}
and the code fragment:
16. C1 obj1 = (C1) new C2();
17. C2 obj2 = (C2) new C3();
18. C2 obj3 = (C2) new C1();
19. C3 obj4 = (C3) obj2;
Which line throws ClassCastException?

Answer options

Correct answer: A

Explanation

Line 18 attempts to cast an instance of C1 to C2, which is not a valid conversion since C1 is the superclass and not a subclass of C2. The other lines either involve valid casts or are not problematic in terms of inheritance.