NickC NickC - 5 months ago 8
Java Question

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

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 conversion. 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();
}

Answer

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