Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List how to set and get children objects of a list of type parent

If I had a linked list of parent objects like:

LinkedList<ParentClass> list = new LinkedList<ParentClass>();

And I wanted to fill them with different types of children objects (that all extend "ParentClass") how would I go about doing this. Also note that I don't know which particular child class will be used. For example I could try to do:

list.add(someInstanceOfAChildClass);

And then be able to access methods and attributes inside that child class. I can clarify if I'm not getting my point across. Thanks in advance!

like image 895
Ben Hagel Avatar asked Feb 28 '15 17:02

Ben Hagel


2 Answers

You would have no problems to fill your List<Parent> with different Child objects but you cannot access Child's methods and attributes directly. If you try to assign a List member to a reference of type Child, you'll get a Type Mismatch error.

To get around this problem you can type cast the object returned by the List explicitly.

Child iThinkItsChild = (Child) listOfParents.get(indexOfChild);

But, to do it safely you should use the instanceof operator first.

Parent parent = listOfParents.get(indexOfChild);
if (parent instanceof Child) {
    Child imSureItsChildNow = (Child) parent;
    imSureItsChildNow.childMethod();
}
like image 75
Ravi K Thapliyal Avatar answered Oct 26 '22 22:10

Ravi K Thapliyal


You just add your subclasses elements. As they extend ParentClass they can be added to any collections that holds ParentClass type.

like image 34
Zielu Avatar answered Oct 26 '22 23:10

Zielu