What is the difference between this:
T getById(Integer id);
And this:
<T> T getById(Integer id);
Are they not both returning a class with type T
?
Yes, but you will have to declare T
somewhere. What changes is where you do.
T
is defined at class level, so your method is part of a generic class and you will have to specialize the class when you declare/instantiate. T
will be the same for all methods and attributes in the class.T
is defined at method level, so it's a generic method. Value for T
can (often) be deduced.In the first case, the scope of T
is the whole class, while in the second is the method only.
The second form is used commonly with static methods. Also, the latter has the advantage that the type variable T
can be deduced (you don't have to specify it in most cases), while you have to specify it for the former.
Specifically, you will have to use a generic class if some attributes of it depend on T
(are of type T
, List<T>
, etc.).
In the first snippet, T
is referring to the type variable declared in the class' type parameter list.
In the second snippet, you are creating a new type variable T
(which may shadow the class one), declared in the method parameter list.
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