Java 在子类中重写构造函数
我对构造函数有以下问题。我正在尝试重写Java 在子类中重写构造函数,java,oop,constructor,super,Java,Oop,Constructor,Super,我对构造函数有以下问题。我正在尝试重写Cel的函数,它是GameObject的子类(GameObject需要x,y,宽度,高度和id)。我想添加xPosGrid和yPosGrid,以确保我知道网格中所有cel的位置。但我不想让构造器太长。所以我想使用第二个构造函数(下面) 但这给了我一个错误 隐式超级构造函数GameObject()未定义。必须显式调用另一个构造函数 谁能告诉我如何避开这个问题吗。我们将不胜感激 //Constructor that does work public Cel(in
Cel
的函数,它是GameObject
的子类(GameObject
需要x
,y
,宽度
,高度
和id
)。我想添加xPosGrid
和yPosGrid
,以确保我知道网格中所有cel的位置。但我不想让构造器太长。所以我想使用第二个构造函数(下面)
但这给了我一个错误
隐式超级构造函数GameObject()未定义。必须显式调用另一个构造函数
谁能告诉我如何避开这个问题吗。我们将不胜感激
//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()
作为子构造函数的第一条语句
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;
}
解决方案:要么向
GameObject
添加一个空构造函数(使其受保护
t避免意外),要么显式调用this
或super
。如果不调用super(…)
或this(…)
编译器会添加super()
。正如错误告诉您的:没有没有参数的超级构造函数。因此,您需要添加此构造函数或使用伪值调用现有的超级构造函数。您错了。对于同一个对象,不能有两个构造函数同时调用它们
当您编写new Cel()
。。。然后你必须给出与你的构造函数中的一个匹配的参数
你不能稍后再打电话给另一个构造器。从这个意义上说:了解子类的基本属性是什么,然后提供一个符合该模型的构造函数。谢谢你的帮助^-^欢迎你。请不要忘记选择一个答案(左边的复选标记)来结束问题。对不起,但是x和xPosGrid之间有什么区别?您不必在类的构造函数中做任何事情:创建一个
SetGridPosition
方法来更新xPosGrid
和yPosGrid
(您可以在构造函数中将它们默认为0.0)