Java OCA OCP Practice Question 1927

Question

Given the following class and reference declarations, what can be said about the statement y = (Sub) x?.

// Class declarations:
class Super {}
class Sub extends Super {}

// Reference declarations:
  Super x;
  Sub y;

Select the one correct answer.

  • (a) Illegal at compile time.
  • (b) Legal at compile time, but might be illegal at runtime.
  • (c) Definitely legal at runtime, but the cast operator (Sub) is not strictly needed.
  • (d) Definitely legal at runtime, and the cast operator (Sub) is needed.


(b)

Note

The statement would be legal at compile time, since the reference x might actually refer to an object of the type Sub.

The cast tells the compiler to go ahead and allow the assignment.

At runtime, the reference x may turn out to denote an object of the type Super instead.

If this happens, the assignment will be aborted and a ClassCastException will be thrown.




PreviousNext

Related