I found this in a java book and would like to understand why am I getting the error as outlined below:
public class Wildcard<V> {
V value;
public Wildcard(V value) {
super();
this.value = value;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public boolean sameObj(Wildcard<? extends V> v1, MyComparator<V> comparator) {
return comparator.compare(this.value, v1.value);
}
public static void main(String[] args) {
Wildcard<Integer> iTest = new Wildcard<Integer>(10);
Wildcard<Number> nTest = new Wildcard<Number>(10);
nTest.sameObject(iTest, new MyComparator<Number>() {
public boolean compare(Number o1, Number o2) {
return o1 == o2;
}
});
}
}
interface MyComparator<V> {
public boolean compare (V value,V value2) ;
}
The syntax error that appears on the line nTest.sameObject
is:
The method sameObject(Wildcard<Integer>, new MyComparator<Number>(){}) is undefined for the type Wildcard<Number>
Since the method is being called on class Wildcard
parameterized with Number
, the first parameter to sameObject
function can be anything that extends V
(Number in this case) and the parameter to the function that appears next should be V
(a Number in this case). Hence it should be a legal call. Why is it not a legal call?