I can't understand the difference between the two code snippets below. Can someone help me with a simple explanation?
First of all, I have to say that I have a lot of classes that extend a super class named BaseEntity
, so what are the differences, benefits and drawbacks of the following snippets?
// 1
public <T extends BaseEntity> T getName(T t) {
return t;
}
// 2
public BaseEntity getName(BaseEntity t) {
return t;
}
The first snippet is more flexible as it preserves the actual type of T
. Suppose you have a subclass:
class SubEntity extends BaseEntity {}
In the first case you can write:
SubEntity result = getName(new SubEntity());
But in the second case you will need a cast:
SubEntity result = (SubEntity)getName(new SubEntity());