OCA Java SE 8 Mock Exam - OCA Mock Question 13








Question

Which of the following statements can be inserted in the blank line so that the code will compile successfully? (Choose all that apply)

     public interface Printable {
     } 

     public class Shape implements Printable {
     } 

     class Rectangle extends Shape {
     } 

     public class Main {   
          public static void main(String[] args) {     
                List<Rectangle> rectangles = new ArrayList<Rectangle>();     
                for(Shape s : rectangles) {       
                  ___________ myShape = s; 
                } 
          } 
     } 
     
  1. Printable
  2. Long
  3. Shape
  4. Rectangle
  5. Object




Answer



A, C, E.

Note

The for-each loop automatically casts each Rectangle object to an Shape reference.

Any parent class or interface that Shape inherits from is permitted without an explicit cast.

A and E are correct.

C is correct since the reference is being cast to the same type, so no explicit cast is required.

B is incorrect, since Long is not a parent of Shape.

D is incorrect, an explicit cast to Rectangle on the right-hand side of the expression is required.