开发者

Why is there a warning on this Java generic method definition?

开发者 https://www.devze.com 2023-01-27 07:03 出处:网络
I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked con开发者_JAVA技巧version. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

 

It makes little sense to me, and Google didn't bring up anything useful. Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

interface Car {
    Car getCar();
}


You've made the method generic, so the caller gets to say what type should be returned (because the caller can specify the type argument). That's a pretty hard interface to implement properly in Java, where you don't get to find out the type argument at execution time.

For example, consider this:

Car mazda = new MazdaRX8();        
FordGalaxy galaxy = mazda.<FordGalaxy>getCar();

That's perfectly legal as far as the interface is concerned... but it's obviously not going to work.

Any reason why the interface isn't generic instead of the method? Then MazdaRX8 would implement Car<MazdaRX8>:

interface Car<T extends Car> {
    T getCar();
}

class MazdaRX8 implements Car<MazdaRX8 > {
    public MazdaRX8 getCar() {
        return this;
    }
}


Short answer: it doesn't work that way, and is extremely dangerous to do what you are proposing since there is no way for the compiler to deduce what should be "correct" there. Generic methods usually have the type passed into them by the method parameters, here you don't pass anything in parameterized so T could be anything that extends Car.

Long answer: Look to this question for the answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消