[英]How to create a class which holds list of any children of a class?
Java doubts: Java疑惑:
let's say I have a class named A. and I have its child classes as A1, A2, A3, etc. as shown below假设我有一个名为 A 的 class,我的子类为 A1、A2、A3 等,如下所示
eg例如
Class A
{
}
Class A1 extends A {
}
Class A2 extends A{}
Class A3 extends A{}
Now I have another class which is ListA class.现在我有另一个 class,它是 ListA class。 this class has an attribute which is basically a list of any children of class A.
这个 class 有一个属性,它基本上是 class A 的任何孩子的列表。
Class ListA<T> {
List<T> listOfChildren;
ListA(int n) {
//some how instantiate the above list based on the generic type.
}
}
}
I have used generic class because I think it is good way to tackle this use case.我使用了通用 class 因为我认为这是解决这个用例的好方法。 But any other suggestions will be helpful.
但任何其他建议都会有所帮助。
Why not use this:为什么不使用这个:
List<? extends ClassA> myList=new ArrayList();
myList.add(myClass);//You will receive an error if you add anything that does not extend from ClassA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.