1Z0-803 · Question #112
Given the class definitrions: class Shape { } class Square extends Shape { } Given the variable declarations: Shape shape1 = null; Square square1 = null; Which four compile?
The correct answer is A. shape1 = (Square) new Square(); B. shape1 = new Square(); C. square1 = (Square) new Shape(); E. square1 = new Square();. This question assesses understanding of Java's object instantiation, assignment compatibility, and casting rules within an inheritance hierarchy.
Question
Given the class definitrions:
class Shape { } class Square extends Shape { } Given the variable declarations:
Shape shape1 = null; Square square1 = null; Which four compile?
Options
- Ashape1 = (Square) new Square();
- Bshape1 = new Square();
- Csquare1 = (Square) new Shape();
- Dsquare1 = new Shape();
- Esquare1 = new Square();
- Fshape1 = new Shape();
How the community answered
(31 responses)- A74% (23)
- D16% (5)
- F10% (3)
Why each option
This question assesses understanding of Java's object instantiation, assignment compatibility, and casting rules within an inheritance hierarchy.
Assigning `new Square()` to `shape1` is a valid upcast since `Square` extends `Shape`; the explicit `(Square)` cast is redundant but harmless and compiles successfully.
Assigning `new Square()` to `shape1` is a valid implicit upcast because a `Square` object is also considered a `Shape` object due to inheritance.
Casting `new Shape()` to `(Square)` and assigning it to `square1` is syntactically valid at compile time, as `Square` extends `Shape`, though it would result in a `ClassCastException` at runtime because `new Shape()` does not create an object that is truly an instance of `Square`.
This is a compile-time error because assigning `new Shape()` directly to a `Square` reference (`square1`) is an implicit downcast, which is not allowed without an explicit cast as a `Shape` is not guaranteed to be a `Square`.
Assigning `new Square()` to `square1` is a direct and valid assignment because both the object being created and the reference variable are of the same `Square` type.
While `shape1 = new Shape();` is syntactically correct when classes are in the same package, it would fail to compile if `Shape` and the code instantiating it were in different packages, as `Shape`'s default constructor is package-private.
Concept tested: Polymorphism, type compatibility, explicit casting
Source: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Topics
Community Discussion
No community discussion yet for this question.