If I have a method, for instance
public INode getNode(final int offset);
I assume it doesn’t add something to make the method return type generic, for instance:
public <T extends INode> T getNode(final int offset);
Or did I miss something? I think generic return types are only of value if one of the parameters is of the same type (or a super/subtype)?
Not only does this not provide any additional information to the caller, but is outright dangerous: The only way to implement that method signature is to use an unchecked cast, which can not be type safe, because a method’s type parameters are specified by its caller (explicitly or implictly through type inference), and the type parameters aren’t available to this method’s implementation. For instance, consider the following program:
Best practice: Don’t use an unchecked cast, unless you are really sure it’ll be type correct at runtime.
There are more cases, for instance:
or
or the examples in Colin’s answer, where the type variable merely appears as type parameter in the return type, which is acceptable due to type erasure.
Edit:
Of course there is, it’s called visitor pattern.