views:

143

answers:

3

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:

  • Z contains 1 Y object.
  • Y and Z are both subclasses of P
  • The image seems to work if you refresh - My reputation is too low to upload images, so I will edit when I acquire 15 points :)
+1  A: 

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

Jon Skeet
Thanks for the straight-forward answer!
destructo_gold
A: 

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.

Péter Török
A: 

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.

DaveJohnston