I have two classes, one in which I have the <T extends Comparable<T>
in the class header iteslf as class MaximumTest2 <T extends Comparable<T>>
and another in which I have public class MaximumTest
but the method extends Comparable as you can see in the code below.
In what way are the implementations different and is one better than other. btw , the way both classes above do the same thing.
class MaximumTest2 <T extends Comparable<T>>
{
// determines the largest of three Comparable objects
public T maximum(T x, T y, T z) // cant make it static but why??
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
}
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] )
{
MaximumTest2 test2 = new MaximumTest2();
System.out.println(test2.maximum(9, 11, 5));
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );
System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}
public T maximum(T x, T y, T z)
static, I get the following error in Eclispe: cannot make a static reference to a non-static type T
. I do not understand what this means? Can I not make it static?Lastly, what is phrase exactly means <T extends Comparable<T>
?
Well, your first declaration makes MaximumTest
generic whereas the second does not; that's a big difference from a programming standpoint (although when all is said and done and your code is compiled, the difference is erased -- that's why you can't declare a generic class and a non-generic class with the same name).
cant make it static but why??
Sure you can; you just need to declare the type parameter T
in the method signature as you do in your second declaration:
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
static
methods can know nothing about the type parameter of the instance, by definition.
Lastly, what is phrase exactly means
<T extends Comparable<T>>
In plain terms, it means T
must be a type such that T
instances are comparable to other T
instances. Specifically, T
must implement the Comparable
interface and consequently support the compareTo()
method, the mechanism through which the comparing is done.