1Z0-808 · Question #95
Given the class definitions: ``java class Shape { } class Square extends Shape { } ` Given the variable declarations: `java 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(). Note: The stated answer (A, B, C, E) appears to contain an error - options F and G also compile by standard Java rules, and a well-formed version of this question would likely ask "which six compile?" or exclude F and G from the choices. Here is the accurate breakdown: Compiles…
Question
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 = square1;
- Gshape1 = new Shape();
- Hsquare1 = shape1;
How the community answered
(34 responses)- A85% (29)
- D9% (3)
- F3% (1)
- H3% (1)
Explanation
Note: The stated answer (A, B, C, E) appears to contain an error - options F and G also compile by standard Java rules, and a well-formed version of this question would likely ask "which six compile?" or exclude F and G from the choices.
Here is the accurate breakdown:
Compiles (A, B, C, E, F, G):
- B, E, G are straightforward: assigning to a reference of the same type (E, G) or a parent type (B) is always valid -
SquareIS-AShape. - F (
shape1 = square1) also compiles for the same reason as B: assigning aSquarereference to aShapevariable is a widening conversion requiring no cast. - A compiles because explicitly casting a
SquaretoSquarebefore assigning to aShapeis redundant but legal. - C (
square1 = (Square) new Shape()) compiles because the compiler permits explicit downcasts when the target type is in the same hierarchy - however, it throws aClassCastExceptionat runtime since the actual object is aShape, not aSquare.
Does not compile (D, H):
- D and H both attempt to assign a parent-type reference to a child-type variable without an explicit cast, which the compiler rejects.
Memory tip: "Widening (up the tree) is free; narrowing (down the tree) needs a cast to compile, but may still explode at runtime."
Topics
Community Discussion
No community discussion yet for this question.