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 🙂
You can’t – assuming you only want to try to call
PrintWson instances of Y, you need to determine which references are pointing at instances of Y… and that’s where you useinstanceof. (You could useY.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
PrintWswhich is then overridden in Y, then you can call it on everything in the list…