I have
class Shape implements Comparable <Shape>
and
class Square extends Shape
I wrote a general method for finding the maximum element inside an array:
public static <S extends Comparable<S>> S findMax(S[] arr)
{
return maxS;
}
These two calls do not give me any errors and do what they should:
Shape maxShape = findMax(new Shape[]{new Shape(1), new Shape(2), new Shape(3)});
Square maxSquare = findMax(new Square[]{new Square(1), new Square(2), new Square(3)});
Therefore, it seems reasonable that, as Shapeimplements Comparable<Shape>and Squarethe extends Shape, Squaremust also be comparable, aka Squaresomehow automatically implements Comparable<Square>through inheritance (in particular, inheriting compareTo(Shape s)).
However, according to my textbook, it is not so here, "all we know is Square implements Comparable<Shape>, therefore, Squarethe IS-A Comparable<Shape>, but-the NOT-the IS A Comparable<Square>", and instead it offers a better method signature:
public static <S extends Comparable<? super S>>.
public static <S extends Comparable<S>> ?
----------------------------- UPDATE (SOURCE CODE) ------------- -----------------
public class Shape implements Comparable<Shape>{
protected int area;
public Shape (int i)
{
this.area=i;
}
public String toString()
{
return area+"";
}
public static void main(String[] args)
{
System.out.println("Bigger shape: "+findMax(new Shape[] {new Shape(2),new Shape(3)}));
System.out.println("Bigger square: "+findMax(new Square[] {new Square(2),new Square(3)}));
}
public int getValue()
{
return area;
}
@Override
public int compareTo(Shape sh) {
return Integer.valueOf(area).compareTo(sh.getValue());
}
public static <N extends Comparable<N>> N findMax(N[] arr)
{
int maxIdx=0;
for (int i=1; i<arr.length; i++)
if (arr[i].compareTo(arr[maxIdx])>0)
maxIdx=i;
return arr[maxIdx];
}
}
class Square extends Shape
{
public Square(int i)
{
super(i);
}
public int compareTo(Shape sh)
{
return Integer.valueOf(area%3).compareTo(sh.getValue()%3);
}
}
Bigger shape: 3
Bigger square: 2
: - . , findMax Square[] - Shape[].