Java OCA OCP Practice Question 1330

Question

Suppose class Square extends class Shape. Given the following code:

Square square = new Square(); 
Shape shape = new Shape(); 

Which lines compile without error? (Choose all that apply.)

  • A. square = shape;
  • B. shape = square;
  • C. square = (Square)shape;
  • D. shape = (Shape)square;
  • E. shape = (Object)square;


B, C, D.

Note

A cast is required when assigning from a superclass to a subclass, so A requires a cast but B does not.

The cast in C is required; the cast in D is not but does no harm.

The cast in E turns the right-hand side of the assignment into an Object, which may not be assigned to a Shape without a cast.




PreviousNext

Related