Reputation: 1311
I have the following abstract class:
public abstract class GameObject {
protected final GameSession session;
protected final int id;
protected Point position;
public GameObject(GameSession session, Point position) {
this.position = position;
this.id = session.getNewId();
this.session = session;
}
public void setPosition(Point position) {
this.position = position;
}
public int getId() {
return id;
}
public Point getPosition() {
return position;
}
Each gameObject
also contains constants WIDTH
and HEIGHT
. I want to add method getBar()
for all game objects which supposed to use these constants. Here an example of game object:
public class Wall extends GameObject {
private static final Logger logger = LogManager.getLogger(Wall.class);
private static final int WIDTH = 32;
private static final int HEIGHT = 32;
public Wall(GameSession session, Point position) {
super(session, position);
logger.info("New Wall id={}, position={}", id, position);
}
And getbar()
if it were in Wall
class:
public Bar getBar() {
return new Bar(position, position.getX() + WIDTH, position.getY() + HEIGHT);
}
How should I implement GameObject
correctly? The problem is that i can't just initialize WIDTH
and HEIGHT
inside because they are different in subclasses.
Upvotes: 2
Views: 1170
Reputation: 14658
Define abstract method getBar() in your abstract class GameObject
public abstract Bar getBar()
Then all classes which extends GameObject
must implement them.
So for example Wall
class will have method
@Override
public Bar getBar() {
return new Bar(position, position.getX() + WIDTH, position.getY() + HEIGHT);
}
Alternatively you can create constructor in GameObject
which will also takes these constants and then you can have single method call (no need to override it):
public abstract class GameObject {
protected final GameSession session;
protected final int id;
protected Point position;
protected final width;
protected final height;
public GameObject(GameSession session, Point position, int width, int height) {
this.position = position;
this.id = session.getNewId();
this.session = session;
this.width = width;
this.height = height;
}
public Bar getBar() {
return new Bar(position, position.getX() + width, position.getY() + height);
}
}
then in your Wall
class
public Wall(GameSession session, Point position) {
super(session, position, 32, 32); //Added WIDTH and HEIGHT
logger.info("New Wall id={}, position={}", id, position);
}
Upvotes: 2