Say A
is an interface. What is the difference between
public <T extends A> void foo(T t) { ... }
and
public void foo(A a) { ...}
?
There isn't a difference when using one object. But imagine if you had
class B extends A { ... }
and
public void f(List<A> list) { ... };
and
public <T extends A> void f(List<T> list) { ... };
with the first one you can pass a list that is exactly of type List<A>
. With the second one you can pass a list which contains objects that extend A
. However, with the first one you cannot do the same thing. So in other words you could not pass List<B>
to the first method but you could to the second method.
Not much.
On the other hand, consider this method:
public <T extends A> T transform(T t);
And caller code:
class B implements A { ... }
B result = transform(new B(...));
It wouldn't be possible (above wouldn't compile, as compiler would force you to declare result
type as A
) had you declared method as
public A transform(A a)
There is no difference in your case because the type parameter is used in one place only. Both methods will accept anything that is an A or extends A. The generic method would make more sense in this case because the type parameter let you tie the return value to the passed parameter:
public <T extends A> T f(Class<T>) {...}
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