1Z0-808 practice question 29 of 30

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?

Full set: 224 questions
Answer options
A: line 18 Correct answer
B: line 17
C: line 19
D: line 16
Correct Answer:
A. line 18
Explanation

A ClassCastException is a runtime exception thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
- Line 16 and 17 are upcasts (C2 to C1, C3 to C2), which are always safe and do not cause exceptions.
- Line 18 attempts to downcast an instance of C1 to C2. Since an object of a superclass (C1) is not an instance of its subclass (C2), this operation fails at runtime and throws a ClassCastException.
- Line 19 casts obj2 (which holds a C3 object) to C3, which is a valid cast.

Why Incorrect

B. Line 17 is a valid upcast. An object of type C3 is also an instance of its superclass C2, so the cast is successful.
C. Line 19 is a valid cast. The variable obj2 refers to an object of type C3 (from line 17), which can be cast to C3.
D. Line 16 is a valid upcast. An object of type C2 is also an instance of its superclass C1, so the cast is successful.

References

1. Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., & Smith, D. (2023). The Java® Language Specification, Java SE 21 Edition. Oracle America, Inc. Section 5.5.1, "Reference Type Casting" and Section 15.16, "Cast Expressions".

2. Oracle, The Java™ Tutorials. "Inheritance". Section: "Casting Objects". (docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)

3. MIT OpenCourseWare. (2010). 6.092 Introduction to Programming in Java. Lecture 8: "Object-oriented programming: Inheritance and polymorphism". (ocw.mit.edu)

Scroll to Top