我写了一个实现了Comparable接口和2个子类的类Fruit:Apple和Orange。 我写了一个方法,返回2个水果之间的最大值(不管它是什么意思)。带有超级意外行为的Java通配符
请注意,我没有使用超级通配符。
我认为max方法会失败,因为Comparable接口不是由Apple或Orange直接实现的。
问: 为什么建议使用这种形式的通配符:
<T extends Comparable<? super T>>
如果它的工作原理也没有超?
下面是代码:
package main;
//Note that I did not use the super wildcard: <T extends Comparable<? super T>>
class Max {
public static <T extends Comparable<T>> T getMax(T x, T y) {
return x.compareTo(y) >= 0 ? x : y;
}
}
class Fruit implements Comparable<Fruit> {
public String name;
public Fruit(String name) {
this.name = name;
}
@Override
public int compareTo(Fruit other) {
return name.compareTo(other.name) == 0 ? 0 :
name.compareTo(other.name) > 0 ? 1 : -1;
}
}
class Apple extends Fruit {
String name;
public Apple(String name) {
super(name);
}
}
class Orange extends Fruit {
String name;
public Orange(String name) {
super(name);
}
}
public class Main {
public static void main(String[] args) {
Apple a = new Apple("apple");
Orange o = new Orange("orange");
Fruit f = Max.getMax(a, o); //It should not be allowed because T does not implement Comparable directly
System.out.println(f.name);
}
}
唯一令人担忧的是子类中外部的'name'字段,它们保持为空,并隐藏'Fruit.name'。您应该使字段最终在'受保护的最终字符串名称;'在水果中,因此它不能被更改,并且可比较合同保持正常。 –
[ super T>什么是语法?](http://stackoverflow.com/questions/2827585/what-is-super-t-syntax) –