Consider this example (typical in OOP books):
I have an Animal class, where each Animal can have many friends.
And subclasses like
You could implement it like this:
@SuppressWarnings("unchecked")
public T callFriend(String name) {
return (T)friends.get(name);
}
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)
The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.
Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:
jerry.callFriend("spike").bark();
While this may be a little nicer than casting, you are probably better off giving the Animal class an abstract talk() method, as David Schmitt said.