Oleg
Oleg

Reputation: 1559

Java bounded type parameters

1.I thought that Interfaces in Java don't have implementations, so how can I use my compareTo() here?

2.As far as I knew the extends keyword can add new methods to an interface in order to be implemented later. So I don't understand what/how am I exactly extending right here ?

Thanks

public class Compare {

    // simple comparison operator < > ... works only on primitives
    // that's why we need the Comparable
    public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
        int count = 0;

        for (T e : anArray)
            if (e.compareTo(elem) > 0)
                ++count;

        return count;
    }
}

Upvotes: 0

Views: 153

Answers (2)

declension
declension

Reputation: 4185

Actually from Java 8 onwards, Interfaces can have (default, partial) implementation, but that's an aside. The confusing thing here is that the keyword extends has two usages:

  1. extending the functionality of classes and, as you correctly say, by analogy the Interface class hierarchies.
  2. For Generic classes, Bounded Type Parameters are used for defining the bounds of a type parameter, e.g. List<T extends Comparable>. Using the same key word was a decision made when they introduced this, presumably to emphasise how the kind of class that is suitable for this Generic T would itself have to extend Comparable (for example). As classes and interfaces in Java share the same hierarchies, it doesn't really matter which you use here (though interfaces are advisable).

Upvotes: 0

Glorfindel
Glorfindel

Reputation: 22631

  1. Interfaces in Java don't have implementations, but you can't create an instance of an interface. (Try it - what happens when you include new List() in your code?) You can only create an instance of a class implementing that interface, and the class is required to implement the interface's methods.

  2. In this case, you're not extending anything at all yourself. You just indicate 'this method can only be used for classes T which extend/implement the Comparable<T> interface'.

Upvotes: 1

Related Questions