I wrote a class Fruit which implements the Comparable interface and 2 subclasses: Apple and Orange. I wrote a method that returns the maximum between 2 fruits (whatever it means).
Note that I did NOT use any wildcards with super.
I thought that the method max would fail because the Comparable interface is not implemented directly by Apple or Orange.
Question: Why is it suggested to use this form of wildcard:
<T extends Comparable<? super T>>
if it works also without super?
Here is the code:
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);
}
}