Expanding on SimonC's answer a little bit.
Consider you have classes:
Result
LoginResult extends Result
OtherResult extends Result
If your type T is OtherResult
then trying to return a LoginResult is nonsense. The compiler will only compile it if it can GUARANTEE sensibility at compile time. As it stands it cannot, since T can be an incompatible type with LoginResult.
A return type of <T extends Result>
does NOT mean that you have to return something that is a Result
. It means that you need to return something that is a T
, but T
has to be a subclass of Result
Regarding your edit
Edit: The reason I want to use generics, is so I can do something like
the following:
Command<LoginResult> login = new Command<>();
LoginResult result = execute( login );
I'm not sure exactly what execute should do, but my first thought is to make execute an instance method of Command.
Then you would have
public T execute()
{
}
The problem is you need a way to instantiate LoginResult
. This is where we need more information into your specific problem to give a detailed answer.
I would make a static method in Result called newInstance. Then since you know T
is some subclass of result you can call T.newInstance()
. Then your would-be constructor for loginResult can be private, and you call it through it's newInstance method.
This requires your Command to be defined as:
public class Command<T extends Result>
And Result must have a method with signature:
public static Result newInstance()
Another concern that may arise is that you don't want to constrain Command to Results. That's fine, you can make a new class:
public class ResultCommand<T extends Result> extends Command