简体   繁体   中英

Java extends class as function argument

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?

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>.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM