[英]Java method that takes only objects that inherit from super class
I would like to have a method in a Java class that will allow me to pass only objects that inherit from super class, fe: 我想在Java类中有一个方法,该方法只允许我传递从父类fe继承的对象:
I have container super class Div
: 我有容器超类
Div
:
package org.gwtbootstrap3.client.ui.html;
public class Div extends ComplexWidget {
public Div() {
setElement(Document.get().createDivElement());
}
}
I would like to use Div
class and its children in the NRowsXNColumns
class: 我想在
NRowsXNColumns
类中使用Div
类及其子级:
public class NRowsXNColumns extends GenericLayout {
public NRowsXNColumns(List<T extends Div> containers) {
// Do something with each container that extends Div class
for(T extends Div container: containers) {
container.display();
}
}
}
Unfortunately it doesn't compile. 不幸的是,它无法编译。
Here you go 干得好
class NRowsXNColumns extends GenericLayout {
public <T extends Div> NRowsXNColumns(List<T> containers) {
for(T container: containers) {
// Do whatever with container
}
}
}
You can restrict types in generics, such as declaring a List<? extends Div>
您可以限制泛型中的类型,例如声明
List<? extends Div>
List<? extends Div>
, but you cannot use that notation when declaring the loop variable container
: List<? extends Div>
,但是在声明循环变量container
时不能使用该表示法:
for (Div container : containers) {
container.display();
}
Since all the objects in containers
must be Div
or a subclass of Div
, they can all be assigned to a variable declared simply as a Div
. 由于所有对象
containers
必须Div
或子类Div
,他们都可以分配到声明只是作为一个变量Div
。
(In a generic method, you can define <T extends Div>
and then declare the list as List<T extends Div>
, but there's no such definition of T
present in this case.) (在通用方法中,您可以定义
<T extends Div>
,然后将列表声明为List<T extends Div>
,但是在这种情况下不存在T
的这种定义。)
Why don't you use just - 您为什么不只使用-
public NRowsXNColumns(List<Div> containers) {
Now you can pass a list of objects which are of Div class or any subclass of Div 现在您可以传递Div类或Div的任何子类的对象列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.