nerdexam
Oracle

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…

Working with Inheritance

Question

Given the class definitions:
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)
  • A
    85% (29)
  • D
    9% (3)
  • F
    3% (1)
  • H
    3% (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 - Square IS-A Shape.
  • F (shape1 = square1) also compiles for the same reason as B: assigning a Square reference to a Shape variable is a widening conversion requiring no cast.
  • A compiles because explicitly casting a Square to Square before assigning to a Shape is 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 a ClassCastException at runtime since the actual object is a Shape, not a Square.

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

#type casting#inheritance#upcasting#downcasting

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice