Java OCA OCP Practice Question 354

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 HasArea {} 
public class Rectangle implements HasArea {} 

class Square extends Rectangle {} 

public class Main {   
   public static void main(String[] args) {     
        List<Square> list = new ArrayList<Square>();     
        for(Rectangle rect : list) {       
            _____ s = rect; // w  ww.ja  va2s. c om
        } 
   } 
} 
A.  HasArea 
B.  Long 
C.  Rectangle 
D.  Square 
E.  Object 


A, C, E.

Note

The for-each loop automatically casts each Square object to an Rectangle reference, which does not require an explicit cast because Square is a subclass of Rectangle.

From there, any parent class or interface that Rectangle inherits from is permitted without an explicit cast.

This includes HasArea, the interface Rectangle implements, and Object, which all classes extend from, so options A and E are correct.

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

Option B is incorrect, since Long is not a parent of Rectangle.

Option D is incorrect as well, although an explicit cast to Square on the right-hand side of the expression would be required to allow the code to compile.




PreviousNext

Related