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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…