简体   繁体   English

用Java调用子类方法

[英]Calling Subclass Method in Java

Given the following situation (UML below), 鉴于以下情况(以下为UML),

If Y has the method: 如果Y具有方法:

public void PrintWs();

and X has: X具有:

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)? 如何遍历每个myPs对象并调用所有Ys PrintW(不使用instanceof)?

http://starbucks.mirror.waffleimages.com/files/68/68c26b815e913acd00307bf27bde534c0f1f8bfb.jpg http://starbucks.mirror.waffleimages.com/files/68/68c26b815e913acd00307bf27bde534c0f1f8bfb.jpg

Sorry, to clarify: 抱歉,请澄清一下:

  • Z contains 1 Y object. Z包含1个Y对象。
  • Y and Z are both subclasses of P Y和Z都是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 :) 如果您刷新图像,该图像似乎可以工作-我的声誉太低,无法上传图像,因此当我获得15分时,我将进行编辑:)

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 . 你不能-假设你只是想尝试调用PrintWs Y上的情况下,你需要确定哪些引用在Y处的情况下,指着...这就是你使用instanceof (You could use Y.class.isInstance(p) but that's just the same thing in a slightly different form.) (您可以使用Y.class.isInstance(p)但这只是同一件事,只是形式略有不同。)

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... 当然,如果您可以使P包含一个无操作的PrintWs ,然后将其替换为Y,则可以在列表中的所有内容上调用它...

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 :-) 好吧,您可以尝试在try块中向下转换到Y并捕获任何ClassCastException ……这不是我会在我的代码中做的事情,但是从字面上看,可以回答您的问题:-)

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. 更好的解决方案是将PrintWs() (默认实现为空)上移到类P然后您可以在myPs所有元素上调用它,而无需向下转换。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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