Java OCA OCP Practice Question 1464

Question

Which variable declaration is the first line not to compile?

class Shape {} 
class Rectangle extends Shape{} 

public void convert() { 
   Shape b =  new Shape(); 
   Rectangle h = new Rectangle(); 
   Shape bh = new Rectangle(); 
   Shape p = (Rectangle) b; 
   Rectangle q = (Shape) h; 
   Shape r = (Shape) bh; //  w w w.  j a  va 2  s  . c o  m
   Rectangle s = (Rectangle) bh; 
} 
  • A. p
  • B. q
  • C. r
  • D. s


B.

Note

Shape and Rectangle are both properly declared inner classes.

Any Rectangle object can be stored in a Shape reference, making the declarations for p and r compile.

The declaration for s is also correct.

bh is a Rectangle object, so the cast works.

The declaration of q is a problem though.

While the cast itself is fine, a Shape cannot be stored in a Rectangle reference, which means the assignment fails to compile.

Option B is correct and is the only line with a compiler error in this code.

If the declaration of q was removed, the declaration of p would produce a ClassCastException at runtime.




PreviousNext

Related