Generic Method with Lower Bound
Lower bounds are useful for cases where we want to be sure that a particular container instantiation can hold a particular element type, without limiting it to just the specific type of the element. For example, consider the following generic method:
Note that T extends Comparable<T>. The Comparable is an generic interface declared in java.lang. This interface declares the compareTo( ) method that is used to determine what Java calls the natural ordering of instances of a class. A class that implements Comparable defines objects that can be ordered. The Comparable interface declared as follows:
The type variable indicates the type of the other parameter. For example, the String class implements Comparable<String>, and its compareTo method is declared as compareTo(String other). Comparable is a generic type so we could have define it as <T extends Comparable<T>. This type declaration ensures that test( ) method take an object of type T that are implements Comparable<T> only. It would work fine for many classes. For example, T is the type String, and String is a subtype of Comparable<String>, or T is the type Integer, and Integer is a subtype of Comparable<Integer> :
But we run into a problem of some situation. Consider the following classes and the call of test( ) method :
The test( ) method cannot be take the type of Data2. Because Data2 extends Data1 and implements Comparable<Data1>. Thus, Data2 implements Comparable<Data1> but not Comparable<Data2>. In a situation such as this one, supertypes come to the rescue :
This is a wildcard instantiation of the Comparable interface. This wildcard instantiation ensures that test( ) method take an object of type T that are implements Comparable<T> or Comparable<supertype of T upto Object>. Thus, the test( ) method take an object of Data2. Besacuse Data2 implements Comparable<Data1>, Data1 is a supertype of Data2.
Program
Program Source
class Data1 { } class Data2 extends Data1 implements Comparable { public int compareTo(Data1 d) { return 10; } } public class Javaapp { static <T extends Comparable<? super T>> void test(T t) { } public static void main(String[] args) { test(new Integer(50)); test(new Data2()); } }