I am surprised that nobody has mentioned this in the previous answers, but there is a more fundamental difference between the two method declarations (which is the reason for the need for casting in the second case). This difference is irrelevant for the trivial methods that you have provided here but it could make a difference for a method that does something different from simply returning its argument.
Your first method declaration requires that the return type be the same type as the argument passed in. So
public <T extends BaseEntity> T getName(T t) {
return new SubEntity(); // Where SubEntity extends BaseEntity
}
fails to compile whereas
public BaseEntity getName(BaseEntity t) {
return new SubEntity(); // Where SubEntity extends BaseEntity
}
is totally legal even if the BaseEntity
passed into the method is a completely different type from SubEntity
.
BaseEntity
as thereturn
value. It can't just be any type of object. In the second snippet, thereturn
value and input parameter can also be subclasses ofBaseEntity
. – Drakensberg