【发布时间】:2013-05-01 20:10:19
【问题描述】:
我有一个名为 Queen 的类,它是 Ant 的子类。 Queen 的构造函数接受参数,并将这些参数传递给 Ants 构造函数,以及 Queen 的其他细节。现在,这就是它应该如何工作的方式。但是我发现 Ant 构造函数从未被调用过。我错过了什么吗?
public class Queen extends Ant
{
public Queen(int width, int height, Square[][] grid)
{
super(0, 0, width, height);
//grid[locationHeight][locationWidth].addQueen(this);
}
}
Ant 构造函数(我在这里有一些 println 语句,但在构造皇后时它们从未被调用过):
public Ant(int id, int type, int width, int height)
{
antID = id;
antType = type;
isAlive = true;
width = width / 2;
height = height / 2;
setLocation(width, height);
if (antType == 0)
{
lifeSpan = 73000;
}
else
{
lifeSpan = 3650;
}
}
【问题讨论】:
-
向我们展示您用于实例化
Queen类的代码。 -
我强烈怀疑您只是误诊了这一点。 Ant 构造函数确实将被调用。
-
编译器会强制Ant的构造函数被调用,为什么你认为它没有被调用?
-
除非你在 Ant/Queen 中有其他构造函数,否则会调用 Ant 的构造函数。
-
提供SSCCE,以便我们复制您所看到的内容。如果你描述了奇怪的异常行为,并且不提供重现它的代码,你会遇到很多怀疑。
标签: java inheritance constructor super