nerdexam
Oracle

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.

Working with Inheritance

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)
  • A
    74% (23)
  • D
    16% (5)
  • F
    10% (3)

Why each option

This question assesses understanding of Java's object instantiation, assignment compatibility, and casting rules within an inheritance hierarchy.

Ashape1 = (Square) new Square();Correct

Assigning `new Square()` to `shape1` is a valid upcast since `Square` extends `Shape`; the explicit `(Square)` cast is redundant but harmless and compiles successfully.

Bshape1 = new Square();Correct

Assigning `new Square()` to `shape1` is a valid implicit upcast because a `Square` object is also considered a `Shape` object due to inheritance.

Csquare1 = (Square) new Shape();Correct

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`.

Dsquare1 = new Shape();

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`.

Esquare1 = new Square();Correct

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.

Fshape1 = new Shape();

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

#inheritance#polymorphism#type casting#upcasting#downcasting

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice