Reputation: 319
Given the following situation (UML below),
If Y has the method:
public void PrintWs();
and X has:
ArrayList <P> myPs = new ArrayList();
Y y = new Y();
Z z = new Z();
myPs.add(y);
myPs.add(z);
How do I loop through each myPs object and call all Ys PrintWs (without using instanceof)?
http://starbucks.mirror.waffleimages.com/files/68/68c26b815e913acd00307bf27bde534c0f1f8bfb.jpg
Sorry, to clarify:
Upvotes: 0
Views: 854
Reputation: 10151
If Y and Z are subclasses of P then you can move the declaration of the method to P with an empty implementation and override it in Y. This way you can call the method on all objects in your ArrayList but only those that are instances of Y will have an implementation for the method.
Upvotes: 0
Reputation: 116266
Well, you could try to downcast to Y
in a try block and catch any ClassCastException
... this is not something I would do in my code, but literally taken, answers your question :-)
A better solution would be to move up PrintWs()
(with an empty default implementation) to class P
- then you can call it on all elements of myPs
without downcast.
Upvotes: 0
Reputation: 1500525
You can't - assuming you only want to try to call PrintWs
on instances of Y, you need to determine which references are pointing at instances of Y... and that's where you use instanceof
. (You could use Y.class.isInstance(p)
but that's just the same thing in a slightly different form.)
Of course if you can make P contain a no-op PrintWs
which is then overridden in Y, then you can call it on everything in the list...
Upvotes: 1