At compile time, javac erases the generic bounded type and replaces it with the upper bound.
For example, the compiler will convert
<T extends Base> void foo(T p) {}
to
void foo(Base p) {}
In this specific case, I think the generics definitely is preferred over the other option. But I would like to know the specific advantages.
Let me explain the need of a Bounded Type properly through an example.
Let's say you are writing a library or framework that are going to used by other. Let's say in somewhere(in some class method) you need to perform some neumerical addition, subtraction, multiplication etc. So, what type of data do you need for that? Of course a Neumeric type. So, what you've done is created a class Number. But, there are various type of numbers like Floating point, Integer etc. So, you've created Integer, Float subclass etc. Now, you've also created a class NumberUtil which gives some features to user like finding average, finding frequency of numbers etc. And of course, in a single word: NumberUtil is awesome, everyone wants to use it. Now, let's talk about the average method in your NumberUtil class(let's write some code):
class NumberUtil<T extends Number> {
T[] nums;
public NumberUtil(T[] nums) {
this.nums = nums;
}
public Double average() {
Double sum = 0.0;
for(int i=0; i<nums.length; i++) {
sum = sum + nums[i].doubleValue(); // note, you've ensured T must be a number
// so, T must able to convert it's value to double value
}
return sum / nums.length;
}
}
Now, let's assume, some other people are using your library, specifically NumberUtil(cause, it's awesome), but they are using it with their own type called SomeNumberType. But it's possible that, this SomeNumberType doesn't subclass Number (or, it doesn't implement the Number interface, if you've declared Number as an interface). So, you can't guarantee that SomeNumberType will provide a doubleValue() method. But, by writing T extends Number, you've made sure in the compile time that SomeNumberType must be a subclass of Number and everything will work fine(at least, it would have the peropeties of Number class, and that means, it'll also have a doubleValue() method).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments