Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cast parent to child?

Tags:

java

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.

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.

Is it not possible to cast a parent class to a child class?

like image 626
Kyle V. Avatar asked Mar 19 '26 05:03

Kyle V.


1 Answers

Your casting syntax is not right.

Try this

if (entity instanceof Beam) {
    ((Beam) entity).age += timeElapsed;
}
else if (entity instanceof Block) {

}
like image 168
Bala R Avatar answered Mar 21 '26 18:03

Bala R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!