Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended class and static variable

I've DynamicObject, Player, Enemy classes

public class DynamicObject {

    protected static float speed;
}



public class Player extends DynamicObject {
       /*some code*/
       Player.speed = 100;
}


public class Enemy extends DynamicObject {
       /*some code*/
       Enemy.speed = 50;
}

And always speed value is overridden. Of course I can create new speed variable in Player and Enemy, but then the existing DynamicObject class is pointless. I want to have different speed values on each class. All objects of current class will have the same speed. How I should make it in correct way?

like image 881
Jakub Pomykała Avatar asked May 08 '26 13:05

Jakub Pomykała


1 Answers

The speed variable should not be static. Otherwise it won't be bound to any of the instances of the DynamicObject class, nor any of it's subclasses instances.

If you want to have a different speed value for each of the subclasses, you can do:

public class DynamicObject {    
    protected float speed;

    public DynamicObject(float speed) {
        this.speed = speed;
    }

    public float getSpeed() {
       return this.speed;
    }
}

public class Player extends DynamicObject {
   /*some code*/
   public Player(float speed) {
       super(speed);
   }

}


public class Enemy extends DynamicObject {
       /*some code*/
   public Enemy(float speed) {
       super(speed);
   }
}
like image 189
Konstantin Yovkov Avatar answered May 10 '26 01:05

Konstantin Yovkov



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!