Java OCA OCP Practice Question 1296

Question

What is the output of the following application?

package mypkg; /*from  w  w  w . j a v  a 2s.c o  m*/
abstract class Shape { 
   protected final int size; 
   public Shape(int size) { 
      this.size = size; 
   } 
} 

interface Printable {} 

public class Rectangle extends Shape implements Printable { 
   public Rectangle() { 
      super(5); 
   } 
   public Shape get() { return this; } 
   public static void main(String[] passes) { 
      Printable p = (Printable)(Shape)new Rectangle().get(); 
      System.out.print(((Rectangle)p).size); 
   } 
} 
  • A. 5
  • B. The code does not compile due an invalid cast.
  • C. The code does not compile for a different reason.
  • D. The code compiles but throws a ClassCastException at runtime.


A.

Note

Although the casting is a bit much, the object in question is a Rectangle.

Since Rectangle extends Shape and implements Printable, it can be explicitly cast to any of those types, so no compilation error occurs.

At runtime, the object is passed around and, due to polymorphism, can be read using any of those references since the underlying object is a Rectangle.

Casting it to a different reference variable does not modify the object or cause it to lose its underlying Rectangle information.

The code compiles without issue, and Option A is correct.




PreviousNext

Related