Java OCA OCP Practice Question 2321

Question

Given the following code

interface Printable{} 
class Shape{} 
class Rectangle extends Shape{} 
class Square extends Shape implements Printable{} 

class Main { //w  ww  . java  2 s.co  m
    public static void main(String args[]) { 
        Shape bird = new Shape(); 
        Rectangle parrot = new Rectangle(); 
        Square vulture = new Square(); 
        //INSERT CODE HERE 
    } 
} 

In which of the following options will the code, when inserted at //INSERT CODE HERE, throw a ClassCastException?.

  • a Square vulture2 = (Square)parrot;
  • b Rectangle parrot2 = (Rectangle)bird;
  • c Printable sc = (Printable)vulture;
  • d Printable sc2 = (Printable)bird;

Note



b, d

ClassCastException is thrown at runtime.

So the options that don't fail to compile are eligible to be considered for the following question: Will they throw a ClassCastException? Option (a) is incorrect because it fails to compile.

Option (b) is correct because classes Shape and Rectangle are in the same hierarchy tree, so an object of base class Shape can be explicitly casted to its derived class Rectangle at compilation.

But the JVM can determine the type of the objects at runtime.

Because an object of a derived class can't refer to an object of its base class, this line throws a ClassCastException at runtime.

Option (c) is incorrect because class Square implements the interface Printable, so this code will also execute without the explicit cast.

Option (d) is correct.

An instance of a nonfinal class can be casted to any interface type using an explicit cast during the compilation phase.

But the exact object types are validated during runtime and a ClassCastException is thrown if the object's class doesn't implement that interface.

Class Shape doesn't implement the interface Printable and so this code fails during runtime, throwing a ClassCastException.




PreviousNext

Related