Skip to content
Advertisement

Storing Objects of multiple classes in an Array List, then accessing their attributes

I have class of (sub)Objects

JavaScript

And a class of Objects

JavaScript

The Objects hold the values height and width and an ArrayList of SubObjects. This works as intended, I do however want to store multiple types of SubObjects from different classes in these ArrayLists.

After a bit of googling I changed the Objects class to

JavaScript

This allows me, as I intended, to store Objects from a second class SubObjects2 inside the ArrayList

JavaScript

This was great and I thought I had solved it, but then I ran the main class and while I, with the earlier implementation could return values with a getter from the objects in the ArrayList

JavaScript

The same query now returns the following error

JavaScript

How do I access the values inside the SubObjects that are stored in the ArrayList now?

Advertisement

Answer

Your problem is that the Object class has no field with the name depth and only SubObject has this attribute

If all of your types have common attributes that you want to get it, you can create an interface and all of them should implement it it for example

JavaScript

and now you will create a list of SubObject and in the loop, it will be

JavaScript

The other solution is to check for the type and cast it before getting the value for example

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement