Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Does a SubClass object in an ArrayList<SuperClass> keep methods unique to SubClass?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...