java Java将父级转换为子级?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6133405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java cast parent to child?
提问by Kyle V.
Here is my code:
这是我的代码:
for (DrawableEntity entity : drawableEntityList) {
if (entity instanceof Beam) {
(Beam) entity.age += timeElapsed;
}
else if (entity instanceof Block) {
}
}
Basically drawableEntityList
is a Vector
of DrawableEntitys
, and I want to iterate through everything in the Vector
. Then depending on if they are subclass Beam
or subclass Block
I want to do something different.
基本上drawableEntityList
是Vector
的DrawableEntitys
,我通过在一切要迭代Vector
。然后取决于它们是子类Beam
还是子类,Block
我想做一些不同的事情。
The problem is that I'm trying to change a variable that only the subclasses have, I figured I could cast with (Beam) but it doesn't work.
问题是我正在尝试更改只有子类具有的变量,我想我可以使用 (Beam) 进行转换,但它不起作用。
Is it not possible to cast a parent class to a child class?
不能将父类转换为子类吗?
回答by Bala R
Your casting syntax is not right.
您的转换语法不正确。
Try this
试试这个
if (entity instanceof Beam) {
((Beam) entity).age += timeElapsed;
}
else if (entity instanceof Block) {
}
回答by Alexandr
Notes: Beware of instanceof
operator
注意事项:小心instanceof
操作员