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!
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();
}
You just add your subclasses elements. As they extend ParentClass they can be added to any collections that holds ParentClass type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With