In this loop, I am iterating through an ArrayList of type Entity, which contains objects of type Entity as well as objects of type Projectile, which extends Entity. I want the below code to be executed if the object is an instance of Projectile. However, the getVelocity() method is only in the subclass Projectile, and not in Entity. So I am unable to compile the below code.
I can think of ways to work around this, such as using separate ArrayLists. However, the point was to keep all Entities within a global list rather than separate them. Is there a simple solution to this problem, or do I need to change the structure of my code?
for (Entity f: glo.getList()) {
if (f instanceof Projectile)
f.setX(f.getVelocity()/rawFPS);
}
You have to cast it as a
Projectilefor it to compile. Try this:This happens because java always checks the type that an object is declared as; In your case this is
Entity.You may want to add a
@SuppressWarnings("unchecked")so that your IDE and anyone that reads your code knows that the unchecked cast is intentional.