Kyle V.
Kyle V.

Reputation: 4802

Java cast parent to child?

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?

Upvotes: 3

Views: 12890

Answers (2)

Alexandr
Alexandr

Reputation: 9515

Notes: Beware of instanceof operator

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

Upvotes: 5

Bala R
Bala R

Reputation: 109037

Your casting syntax is not right.

Try this

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

}

Upvotes: 6

Related Questions