Why is there a warning in this Java generic method definition?
I noticed that if I use generic method signature to complete something similar to the return type of common type, it works just as I thought, except that it will generate a warning:
interface Car { <T extends Car> T getCar(); } class MazdaRX8 implements Car { public MazdaRX8 getCar() { // "Unchecked overriding" warning return this; } }
Using the above code, my ide warns: "unchecked override: the return type requires an unchecked conversion. Find: 'mazdarx8', need't '
What does this warning mean?
It doesn't make any sense to me. Google doesn't come up with anything useful Why isn't this a warning free replacement for the following interface (which is also free because Java allows similar return types)?
interface Car { Car getCar(); }
Solution
You have made the method generic, so the caller gets what type to return (because the caller can specify the type parameter) This is a good interface and can be implemented correctly in Java. Here you won't find type parameters during execution
For example, consider:
Car mazda = new MazdaRX8(); FordGalaxy galaxy = mazda.<FordGalaxy>getCar();
As far as the interface is concerned, this is perfectly legal, but it obviously won't work
Any reason why interfaces are not generic rather than methods? Then mazdarx8 will implement car < < mazdarx8 >:
interface Car<T extends Car> { T getCar(); } class MazdaRX8 implements Car<MazdaRX8 > { public MazdaRX8 getCar() { return this; } }