Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between <T extends A> void foo(T t) and void foo(A a)

Tags:

java

generics

Say A is an interface. What is the difference between

public <T extends A> void foo(T t) { ... }

and

public void foo(A a) { ...}

?

like image 959
Japer D. Avatar asked Dec 06 '11 22:12

Japer D.


3 Answers

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.

like image 194
Amir Raminfar Avatar answered Sep 22 '22 05:09

Amir Raminfar


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)
like image 42
Victor Sorokin Avatar answered Sep 21 '22 05:09

Victor Sorokin


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>) {...}
like image 43
FelixM Avatar answered Sep 21 '22 05:09

FelixM