[英]Java extends class as function argument
Not new to java, but this question bothers me. 对java来说并不陌生,但这个问题困扰着我。 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
. 假设
A
, B
, C
和B extends A
和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? 我的问题是,如何定义方法
f()
以便它可以将List<A>
, List<B>
和List<C>
作为参数?
Use an upper-bounded wildcard: 使用上限通配符:
f(List<? extends A> list)
See Oracle's tutorial for more information. 有关更多信息,请参阅Oracle的教程 。
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>.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.