The type parameters could be replaced by any class type. This is fine for many purposes, but sometimes it is useful to limit the types that can be passed to a type parameter
Syntax :
<T extends superclass
>
Bounded type parameters can be used with methods as well as classes and interfaces.
Generics
supports multiple bounds also, i.e <T extends A & B & C>. In this case A can be an interface
or class.
If A is class
then B and C should be interfaces. We can’t have more than one class
in multiple bounds.
Assume that you want to create a generic class that contains a method that returns the average of an array of numbers. Furthermore, you can use the class to obtain the average of an array of any type of number, including integers, floats, and doubles.
Bounded Types
class AverageDemo
{
public static void main (String args[])
{
Integer integerNumbers[] = {1, 2, 3, 4, 5};
Average<Integer> integerObject = new Average<Integer>(integerNumbers);
double average = integerObject.getAverage();
System.out.println("The average value of given integers is : " + average);
String strs[] = {"A", "B", "C", "D"};
// Average<String> stringObject = new Average<String>(strs); // LINE A
}
}
class Average<T extends Number> { // LINE B
T[] numbers;
public Average(T[] numbers)
{
this.numbers = numbers;
}
double getAverage()
{
double sum = 0.0;
for(int i = 0; i< numbers.length; i++)
{
sum += numbers[i].doubleValue(); // LINE C
}
return sum / numbers.length;
}
}
OUTPUTThe average value of given integers is : 3.0
DESCRIPTIONHere Number
class acts as a super class. Without extends Number at LINE B
we try to run the program. The compiler gives compile time error at LINE C,
since all numeric classes such as Integer
and Double
are subclasses of Number,
and Number
defines doubleValue().
If you uncomment the LINE A
it gives compilation error since String
class does not come under Number
class.
THINGS TO TRY
- Put class Average<T> instead of
class Average<T extends Number>
, compilation error occured at LINE C.
- Uncomment the line at
LINE A
and try to run it. It gives a compile time error.
- Create one more
object
for Double
in AverageDemo
and print the average of {1.5, 2.1, 3.3} double array.