Java OCA OCP Practice Question 1334

Question

Suppose classes Square and Rectangle extend class Shape.

Which statements are true regarding the following code?

1. Rectangle g = new Rectangle(); 
2. Shape c = (Shape)g; 
3. Square lem = (Square)c;  
  • A. The cast in line 2 is not necessary.
  • B. Line 3 causes a compiler error.
  • C. The code compiles, and throws an exception at line 3.
  • D. The code compiles and runs without throwing any exceptions.


A, C.

Note

Line 2 is an assignment from a subclass to a superclass, so the cast is not necessary.

Line 3 compiles because it obeys the compile-time casting rules.

At runtime, the JVM notices that the class of the object referenced by c is not compatible with the Square class, so an exception is thrown.




PreviousNext

Related