Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/generic-methods-in-java
Question 209 / 297:  Will the following code compile?
Choose 2
import java.util.*;

class B {

}

class C extends B {

}

public class Test {

public static <E extends B> Queue<E> ring(List<E> list) {

return null;

}

public static void main(String[] args) {

List<C> list1 = new ArrayList<C>();

ArrayList<C> list2 = new ArrayList<C>();

Queue<C> q1;

PriorityQueue<C> q2;

q1 = ring(list1); // line1

q1 = ring(list2); // line2

q2 = ring(list1); // line3

q2 = ring(list2); // line4

}

}

<< First < Previous Next > Last >>
Explanation:

Let's examine first the return type of method ring():

The return type of ring method is Queue<E>. E is anything that extends B, which is in this case C. Which means only objects of declared type Queue<C> can be assigned the return of ring method()

So, at line1 and line2 assigning the result to q1 (Queue<C> declared type object) will pass

But, at line3 and line 4 assigning the result to q2 (PriorityQueue<C> declared type object) will fail (cannot convert from Queue<C> to PriorityQueue<C>)

Now let's examine the type of the argument of method ring():

The declaration type of the argument is List<E>, E is anything that extends B, which is in this case C.

The passing parameter to method ring can be declared (declaration type) as List or any of List's sub types (ArrayList, LinkedList,..)

You can send non-generic lists of these types or generic list of these types. But, in case of sending a generic list, then the generic type of the List must be C

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Dewey Compton
Start Exam
Jugnu Khan
Start Quiz
Saylor Foundation
Start Quiz
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>