I have the following code:
public class Foo {
interface Coo<T> {
public T cool();
}
abstract class Bar<T extends Bar<T>> implements Coo<T> {
@SuppressWarnings("unchecked")
T doSomething() {
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T cool() {
return (T) this;
}
}
class FooBar extends Bar<FooBar> {
@Override
public FooBar cool() {
return super.cool();
}
}
}
Why is the cast to (this) object type unsafe? When Bar implements Coo, isn’t the generic saying that returned cool must be of type T, which extends Bar or its subclasses?
Because
thisinBarhas typeBar<T extends Bar<T>>but notT, the compiler generates warnings forBar#doSomething. The following won’t generate any warnings:The body of
Bar#coolexpectsthisto be a subtype ofTwhich is not the case. InBar#cool,thishas typeBar<T extends Bar<T>>and is a subtype ofCoo<T>but notT.