wildcards in generic method of an interface

H

HK

Consider the following interface:


import java.util.List;
public interface Action<CDTA> {
void invoke(List<? extends CDTA> r);
}

Now I try to implement it like this:

private static class Xaction implements Action<Number> {
public void invoke(List<Number> l) {
// not yet implemented
}
}

The compiler, however, complains that Xaction does not
implement Action. I can only guess that type-safety
would break if the implementation was allowed. But how?

Can someone give an example that goes wrong if the
above is allowed?

Harald.
 
S

Stefan Schulz

Consider the following interface:


import java.util.List;
public interface Action<CDTA> {
void invoke(List<? extends CDTA> r);
}

Now I try to implement it like this:

private static class Xaction implements Action<Number> {
public void invoke(List<Number> l) {
// not yet implemented
}
}

The compiler, however, complains that Xaction does not
implement Action. I can only guess that type-safety
would break if the implementation was allowed. But how?

Can someone give an example that goes wrong if the
above is allowed?

Suppose someone calls your invoke method with a List<Double> Perfectly
fine with the declaration given in your interface. Now, a List<Double> is
not a List<Number>. A List<Number> can contain nothing but Integers, for
example. You can add Integers into a List<Number>, but not into a
List<Double>. Therefore, you must not "downcast" in contents types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top