Java List how to set and get children objects of a list of type parent
inheritance, java, linked-list, parent-child
Solution
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();
}
Problem
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!