Java OCA OCP Practice Question 1494

Question

Which variable declaration is the first line to throw a ClassCastException at runtime?

class Shape {} 
class Rectangle extends Shape{} 
 
public void convert() { 
  Shape b =  new Shape(); 
  Rectangle h = new Rectangle(); 
  Shape bh = new Rectangle(); 
  Rectangle p = (Rectangle) b; 
  Rectangle q = (Rectangle) h; 
  Rectangle r = (Rectangle) bh; 
} 
  • A. p
  • B. q
  • C. r
  • D. None of the above


A.

Note

The reference b points to a Shape object, which cannot be stored in a Rectangle reference.

The assignment to p compiles but fails at runtime.

The other two casts would run without issue if the code got that far.




PreviousNext

Related