Java抽象类常量

时间:2017-10-15 13:26:02

标签: java

我有以下抽象类:

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还包含常量WIDTHHEIGHT。我想为所有应该使用这些常量的游戏对象添加方法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?问题是我不能在内部初始化WIDTHHEIGHT,因为它们在子类中是不同的。

1 个答案:

答案 0 :(得分:2)

在抽象类GameObject

中定义抽象方法getBar()
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);
}