简体   繁体   中英

How to create a class which holds list of any children of a class?

Java doubts:

let's say I have a class named A. and I have its child classes as A1, A2, A3, etc. as shown below

eg

Class A 
{

}

Class A1 extends A {
}

Class A2 extends A{}
Class A3 extends A{}


Now I have another class which is ListA class. this class has an attribute which is basically a list of any children of 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM