Java OCA OCP Practice Question 2917

Question

Given:

2. import java.util.*;  
3. interface Shape { }  
4. class Rectangle implements Shape { }   
5. public class Main extends Rectangle {  
6.   public static void main(String[] args) {  
7.     List<Rectangle> d = new ArrayList<Rectangle>();  
8.     List<Main> c = new ArrayList<Main>();  
9.     d.add(new Main());  
10.     c.add(new Main());  
11.     do1(d);   do1(c);  
12.     do2(d);   do2(c);  
13.   }  /*from   w  ww. j a v a 2  s. c om*/
14.   static void do1(List<? extends Rectangle> d2) {   
15.     d2.add(new Main());  
16.     System.out.print(d2.size());  
17.   }  
18.   static void do2(List<? extends Shape> c2) {  }  
19. } 

Which are true? (Choose all that apply.)

  • A. Compilation succeeds.
  • B. Compilation fails due to an error on line 9.
  • C. Compilation fails due to an error on line 14.
  • D. Compilation fails due to an error on line 15.
  • E. Compilation fails due to an error on line 16.
  • F. Compilation fails due to an error on line 18.
  • G. Compilation fails due to errors on lines 11 and 12.


D is correct.

Note

When a method takes a wildcard generic type, the collection can be accessed or modified, but not both.

The rest of the code is legal.

It's legal to add a subclass element to a typed collection.

It's legal for a method's argument to be a typed wildcard interface.




PreviousNext

Related