Java extends class as function argument

Not new to java, but this question worries me. I think I don't have a solid foundation.

Suppose that the 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 from List<A>

, List<B>

and List<C>

as an argument?

+3


source to share


1 answer


Use an extended constraint pattern:

f(List<? extends A> list)

      

See Oracle tutorial for details .



Note that this only restricts you to list things in the body of the method; you cannot call consumer methods on a list:

A item = list.get(0);  // OK.
list.add(new A());     // Not OK! list might be a List<B>.

      

+6


source







All Articles