Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java extends class as function argument

Tags:

java

Not new to java, but this question bothers me. I think I do not have a solid foundation.

Let's say have classes A, B, C and B extends A and C extends A. My question is, how can I define a method f() so that it can take one of List<A>, List<B> and List<C> as argument?

like image 249
Yi Luo Avatar asked Jun 16 '26 14:06

Yi Luo


1 Answers

Use an upper-bounded wildcard:

f(List<? extends A> list)

See Oracle's tutorial for more information.

Note that this restricts you to only be able to get things out of the list in the method body; you can't call consumer methods on the list:

A item = list.get(0);  // OK.
list.add(new A());     // Not OK! list might be a List<B>.
like image 149
Andy Turner Avatar answered Jun 19 '26 03:06

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!