Domanda

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?

È stato utile?

Soluzione

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);
   }
}

Altri suggerimenti

If every DynamicObject has a speed, and the speed is the same for every instance of, for example, Player, then you should have

public abstract int getSpeed();

in DynamicObject, and

@Override
public int getSpeed() {
    return 100;
}

in Player.

If you need to have access to the constant speed returned for evry instance of Player without instantiateing a Player, just use

public static final int CONSTANT_PLAYER_SPEED = 100;

@Override
public int getSpeed() {
    return 100;
}

and use Player.CONSTANT_PLAYER_SPEED to access the speed of all players.

Remove the static from that variable, if a variable is static, it's belong to the class, not to instances.

And making a static variable protected doesn't make any scene, since, inheritance and static are totally different.

protected float speed;

You could also have an abstract method, which would mean that you would always have to override it in your sub classes.

public abstract class Dynamic {

protected float speed; 

abstract void setSpeed();
}
public class Player extends Dynamic{
@Override
void setSpeed() {
    this.speed=50;
}

}

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top