Reputation: 2012
The following code gives a compilation error. How coud I avoid this?
public class C<T> {
public T doStuff(T arg) {}
}
public class S<T extends Number> extends C<T> {
public T doStuff(T arg) {
return new Integer(0);
}
}
Thanks!
Upvotes: 1
Views: 51
Reputation: 106440
So this declaration is illegal because, while you've said that T
is some kind of Number
, there's no way to specifically mandate that T
is specifically an Integer
at all times.
public T doStuff(T arg) {
return new Integer(0);
}
That T
may very well be a Long
or a Float
or a BigInteger
, none of which are Integer
.
Luckily, Number
has the intValue()
method, which allows you to get an int from any of those Number
types. You can use that instead:
public Integer doStuff(T arg) {
return new Integer(arg.intValue());
}
You are going to have to change the way your doStuff
method works in the parent class, though; introduce a new type parameter to the method.
public <S> S doStuff(S arg) {
return arg;
}
Of course, this means now that the doStuff
method is unbound as well. If you really wanted to keep the bounds on Number
for the entire class, you would have to have your class use the actual concrete type you cared about.
class S extends C<Integer> {
public Integer doStuff(Integer arg) {
return 0;
}
}
Upvotes: 2