Yi Luo
Yi Luo

Reputation: 169

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?

Upvotes: 3

Views: 70

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

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

Upvotes: 6

Related Questions