Does a SubClass object in an ArrayList<SuperClass> keep methods unique to SubClass?
arraylist, inheritance, java
Solution
The objects themselves are still a `subclass`, but when you get them out of the collection it only knows about the `superclass` so it can't tell you which is which, it has to pick the common denominator.
If you know exactly that a specific index holds an object of type `Subclass` you can just cast it:
Subclass myObject = (Subclass) list.get(0);
System.out.println(myObject.getQuantity());
And it should work.
And a safer way requires testing if the object is really what you think it is:
SuperClass myObject = list.get(0);
if ( myObject instanceof Subclass) {
Subclass mySubObject = (Subclass) myObject;
System.out.println(mySubObject.getQuantity());
}
The first example raises an exception if the object is not of type `Subclass`, the second one wouldn't since it tests before to make sure.
What you need to understand here is that `SuperClass myObject = list.get(0)` is not the object itself, but a reference to access the object in memory. Think about it as a remote that allows you to control your object, in this case, it's not a fully featured remote, since it doesn't show you all your object can do, so you can switch to a better one (as in `Subclass myObject = (Subclass) list.get(0)`) to be able to access all features.
I'd surely recommend the Head First Java book as it covers this stuff in great detail (and I stole this remote example from there).
Problem
Basically what the title says, but some elaboration. I have a SuperClass with a couple of SubClasses. I needed an ArrayList to hold both types of Subclasses so hence the ArrayList of type SuperClass. I tried to access Subclass1's `getQuantity()` method using `ArrayList.get(0).getQuantity();` (assuming that index 0 is of type SubClass1). I get the error: getQuantity is undefined for the type SuperClass. Do the SubClass objects not keep their properties when put into a SuperClass ArrayList? And if they do keep their properties, how do I access them?