我有以下抽象类:
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;
}
每个gameObject
还包含常量WIDTH
和HEIGHT
。我想为所有应该使用这些常量的游戏对象添加方法 getBar()
。这是游戏对象的示例:
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);
}
以及 getbar()
(如果它位于 Wall
类中):
public Bar getBar() {
return new Bar(position, position.getX() + WIDTH, position.getY() + HEIGHT);
}
我应该如何正确实现GameObject
?问题是我不能只在内部初始化 WIDTH
和 HEIGHT
因为它们在子类中是不同的。
最佳答案
在抽象类中定义抽象方法 getBar() GameObject
public abstract Bar getBar()
然后所有扩展 GameObject
的类都必须实现它们。
例如 Wall
类将有方法
@Override
public Bar getBar() {
return new Bar(position, position.getX() + WIDTH, position.getY() + HEIGHT);
}
或者,您可以在 GameObject
中创建构造函数,该构造函数也将采用这些常量,然后您可以进行单个方法调用(无需覆盖它):
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);
}
}
然后在您的 Wall
类中
public Wall(GameSession session, Point position) {
super(session, position, 32, 32); //Added WIDTH and HEIGHT
logger.info("New Wall id={}, position={}", id, position);
}
关于Java抽象类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46755510/