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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:29:20  来源:igfitidea点击:

Java cast parent to child?

java

提问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 drawableEntityListis a Vectorof DrawableEntitys, and I want to iterate through everything in the Vector. Then depending on if they are subclass Beamor subclass BlockI want to do something different.

基本上drawableEntityListVectorDrawableEntitys,我通过在一切要迭代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 instanceofoperator

注意事项:小心instanceof操作员

http://www.javapractices.com/topic/TopicAction.do?Id=31

http://www.javapractices.com/topic/TopicAction.do?Id=31