Saturday, August 28, 2010

Illegal invocation

Courtesy of Sun Web Learning Center


Given:

2. import java.util.*;
3. class Beta extends Alpha {
4.   public static void go(Set<Alpha> set) { }
5.   public static void main(String [] args) {
6.     Set<Alpha> setA = new TreeSet<Alpha>();
7.     Set<Beta> setB = new TreeSet<Beta>();
8.     Set<Object> setO = new TreeSet<Object>();
9.     // insert code here
10.   }
11. }
12. class Alpha { }

And the three code fragments:

s1.   go(setA);
s2.   go(setB);
s3.   go(setO);

Which, inserted independently at line 9, will compile?


A only s1
B only s2
C only s3
D only s1 and s2
E only s1 and s3
F All the codes will compile.

A is correct. Codes s2 and s3 attempt to make an illegal invocation of the go method that takes only a Set of Alphas.
However, if you changed line 4 such that go will accept Set<? extends Object>, then all three code fragments, inserted independently at line 9 will work.

No comments:

Post a Comment