Java OCA OCP Practice Question 2487

Question

Given:

3. class A { }  
4. class B extends A { }  
5. class C extends B { }  
6. public class Carpet<V extends B> {  
7.   public <X extends V> Carpet<? extends V> method(Carpet<? super X> e) {  
8.     // insert code here   
9. } } 

Which, inserted independently at line 8, will compile? (Choose all that apply.)

  • A. return new Carpet<X>();
  • B. return new Carpet<V>();
  • C. return new Carpet<A>();
  • D. return new Carpet<B>();
  • E. return new Carpet<C>();


A and B are correct.

Note

The generic declaration at the class level says that Carpet can accept any type which is either B or a subtype of B.

The generic declaration at the method level is "<X extends V>", which means that X is a type of V or a subtype of V, where the class type of V can vary at runtime-hence, the exact scopes of X and V are unknown at compile time.

A and B are correct because X and V bind to the scope of <? extends V>, where X is known as a subtype of V as it's declared at the method level.

C, D, and E are incorrect because it's illegal to use a concrete class type since the exact scope of V is unknown.




PreviousNext

Related