0

Comparable is an interface which contains the method compareTo().

In the code that uses a generic method to return the largest of three comparable objects, compareTo() method is used directly without implementation. How is that possible? Is it because we are"extending" that interface in the class and not "implementing" it?

public class Max {

    public static <T extends Comparable <T>> T maximum(T x, T y, T z) {
        T max=x;

        if (y.compareTo(max) > 0)
            max=y;

        if (z.compareTo(max) > 0)
            max=z;

        return max;
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Mithra
  • 19
  • 5

1 Answers1

0

Since you declare T extends Comparable<T> any object passed with the type T must implement the Comparable interface.

T can be any object of your choosing as long as it has YourType implement Comparable<YourType>. So whatever you pass to your maximum method has implemented compareTo.

Edit: Oh and the syntax is admittedly a bit confusing with generics. If you add extends SomeInterface to your generic type, it expects an implements and not an extends.

JensV
  • 3,997
  • 2
  • 19
  • 43
  • But I suppose "extends" can be used in general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). – Mithra Oct 31 '19 at 15:27
  • @Mithra yeah that's what it means in this case. I just wanted to point out the possibly confusing syntax in case that was the reason of confusion. – JensV Oct 31 '19 at 15:30
  • 1
    @Mithra Note that for maximum flexibility you should be using `>` (see [here](https://stackoverflow.com/questions/25779184/)). – Slaw Oct 31 '19 at 16:46