简体   繁体   中英

When overloading bounded generics, how can I return the right type?

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!

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM