OCA Java SE 8 Mock Exam 2 - OCA Mock Question 34








Question

Which of the following lines of code can be individually inserted at //INSERT CODE HERE so that the output of the code is as follows:

class Shape { 
    void print() { 
        System.out.println("Shape - A"); 
    } 
} 
class Rectangle extends Shape { 
    void print() { 
        System.out.println("Rectangle - B"); 
    } 
} 
class Main { 
     public static void main(String[] args) {
    
        Shape a = new Shape(); 
        // INSERT CODE HERE 
        a.print(); 
        b.print(); 
     }
} 


Shape - A
Rectangle - B
  1. Shape b = new Shape();
  2. Shape b = new Rectangle();
  3. Rectangle b = new Rectangle();
  4. Rectangle b = new Shape();
  5. Shape b = ((Rectangle)new Shape());
  6. Rectangle b = ((Rectangle)new Shape());




Answer



B, C

Note

A is incorrect. This code will compile, but because both the reference variable and object are of type Shape.

D is incorrect. This code will not compile. You can't assign an object of a base class to a reference variable of a derived class.

E is incorrect. This line of code will compile successfully, but it will fail at runtime with a ClassCastException.

An object of a base class can't be cast to an object of its derived class.

F is incorrect. The expression ((Rectangle)new Shape()) is evaluated before it can be assigned to a reference variable of type Rectangle.