I was going through the code of commons-chain
I found a lot of method signatures resembling this one:
public <CMD extends Command<K, V, C>> CMD getCommand(String commandID)
How is this signature any different from:
public Command getCommand(String commandID)
The only logical reason i could understand was to do type checking. but i still could not figure out the reason to do it from a design point of view.
Are there some more reasons why one would use and extends in return type of a java method?
The name together with the number and types of a method's parameter list is called the signature of a method. The return type itself is not part of the signature of a method.
Method signature does not include the return type of the method. A class cannot have two methods with same signature.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.
Method Signature According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.
The difference is three fold:
And being a typed method, java can infer the type
All this means that this will compile (without casts):
Command<String, Integer, String> x = getCommand(commandID);
or
SomeTypedSubClassOfCommand x = getCommand(commandID);
The compiler will infer (ie figure out) the type for the method based on the type of the variable the result is being assigned to.
Further, you can explicitly specify a subclass with this syntax:
Command<String, Integer, String> x = ContainingClass.<CommandSubClass<String, Integer, String>>getCommand(commandID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With