简体   繁体   中英

Calling Subclass Method in Java

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

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.

如果Y和Z是P的子类,则可以使用空的实现将方法的声明移到P并在Y中覆盖它。这样,您可以在ArrayList中的所有对象上调用该方法,但仅对那些是Y实例的对象进行调用。将有该方法的实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM