Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extends keyword in return type in java method signature

Tags:

java

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?

like image 500
shoubhik Avatar asked Apr 20 '13 23:04

shoubhik


People also ask

Does return type include in signature?

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.

Does method signature include return type Java?

Method signature does not include the return type of the method. A class cannot have two methods with same signature.

What is the keyword used to in place of the return type in a method signature in case the method does not return anything?

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.

Can return types affect method signatures?

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.


1 Answers

The difference is three fold:

  1. The type returned is typed (not a raw type)
  2. The type returned can be a specific subclass
  3. The method has access to the types K, V and C

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);
like image 143
Bohemian Avatar answered Oct 01 '22 21:10

Bohemian