[英]access method in subclass
I have used the code: 我使用了代码:
//change size of raven
birdsByKey.get(instructions[0]).SizeRaven(newSize);
in order to try change the size of the raven. 为了尝试改变乌鸦的大小。
What should I do to use the following method (in class "Raven")? 我该怎么做才能使用以下方法(在“ Raven”类中)?
birdsByKey.get()
is going to return a Bird
. birdsByKey.get()
将返回Bird
。 A Bird
won't have a changeRavenSize()
method (since that is unique to a Raven). Bird
不会具有changeRavenSize()
方法(因为它是Raven唯一的)。
You need something like: 您需要类似:
Bird b = birdsByKey.get(instructions[0]);
if (b instanceof Raven) {
Raven r = (Raven)b;
r.changeSizeRaven(newSize);
}
As EJP mentions, you really want a changeSize()
method for Bird
which Raven
will override. 正如EJP所提到的,您确实想要
Raven
将覆盖的Bird
的changeSize()
方法。 Then you code becomes 然后你的代码变成
birdsByKey.get(instructions[0]).changeSize(newSize);
the first way you need to edit every time you add a new type of bird. 第一种方法是每次添加新类型的鸟时都需要进行编辑。 The second way just add as many birds as you like and it'll just keep working...
第二种方法是添加任意数量的鸟,它将继续工作...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.