在子类中重做构造函数

Reworking a constructor in a subclass

我对构造函数有以下问题。我正在尝试重写 Cel 的函数,它是 GameObject 的子类(GameObject 需要 xywidthheight 和一个 id)。我想添加 xPosGridyPosGrid 以确保我知道所有 Cel 在网格中的位置。但我不想让构造函数非常长。所以我想使用第二个构造函数(在下面)。

但这给了我一个错误

Implicit super constructor GameObject() is undefined. Must explicitly invoke another constructor

谁能告诉我如何解决这个问题。将不胜感激。

//Constructor that does work
public Cel(int x, int y, int width, int height, ID id) {
    super(x, y, width, height, id);
}

//Constructor that doesn't work
public Cel(int xPosGrid, int yPosGrid, Grid grid, ID id) {

    x = grid.x + grid.celWidth * xPosGrid;
    y = grid.y + grid.celHeight * yPosGrid;
    width = grid.celWidth;
    height = grid.celHeight;
    this.id = id;
    this.xPosGrid = xPosGrid;
    this.yPosGrid = yPosGrid;
}

//GameObject Constructor
public GameObject(int x, int y, int width, int height, ID id) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.id = id;
}

您始终需要在构造函数中首先调用超级构造函数。

public Cel(int x, int y, int width, int height, ID id) {
    super(x, y, width, height, id);
}

public Cel(int xPosGrid, int yPosGrid, Grid grid, ID id) {
    super(0,0,0,0,id);
    x = grid.x + grid.celWidth * xPosGrid;
    y = grid.y + grid.celHeight * yPosGrid;
    width = grid.celWidth;
    height = grid.celHeight;
    this.id = id;
    this.xPosGrid = xPosGrid;
    this.yPosGrid = yPosGrid;
}

如果你可以设置x和y以及宽度和高度,你稍后修改它

public Cel(int xPosGrid, int yPosGrid, Grid grid, ID id) {
    super(0,0,0,0,id);
    x = grid.x + grid.celWidth * xPosGrid;
    y = grid.y + grid.celHeight * yPosGrid;
    width = grid.celWidth;
    height = grid.celHeight;
    this.id = id;
    this.xPosGrid = xPosGrid;
    this.yPosGrid = yPosGrid;

    // do some calculations to caluclate the pos and dimensions.

    this.setX(x);
    this.setY(y);
    this.setWidth(width);
    this.setHeight(height);
}

您的 GameObject 似乎没有定义空构造函数。如果省略对 super 的调用,Java 将隐式添加 super() 作为子构造函数的第一条语句。

解决方案:向 GameObject 添加一个空构造函数(使其 protected 避免意外)或显式调用 thissuper

如果您不调用 super(...)this(...),编译器会添加 super()。正如错误告诉你的那样:没有没有参数的超级构造函数。因此,您需要添加此构造函数或使用虚拟值调用现有的超级构造函数。

错了。你不能有两个构造函数并为同一个对象调用它们 both

当您编写 new Cel() ... 时,您必须提供与 一个 构造函数完全匹配的参数。

您以后不能再调用另一个构造函数。从这个意义上讲:了解子类的基本属性是什么,然后提供 one 构造函数来适应该模型。