我对这两个类有一个问题:
生物:
public abstract class Creature extends Texturable
{
public Creature(String ID)
{
this.ID = ID;
} // end Creature()
protected void setMaximumHealthPoints(int maximumHealthPoints)
{
this.maximumHealthPoints = maximumHealthPoints;
} // end setMaximumHealthPoints()
protected void setMaximumSpeed(int maximumSpeed)
{
this.maximumSpeed = maximumSpeed;
} // end setMaximumSpeed()
...
protected String ID;
protected int maximumHealthPoints;
protected int maximumSpeed;
...
} // end Creature人类:
public class Human extends Creature
{
public Human(String ID)
{
this.ID = ID;
setMaximumHealthPoints(100);
setMaximumSpeed(4);
} // end Human()
} // end Human我想做的是,正如上面的代码所说,将最大生命点设置为100,将最大速度设置为4,但仅针对人类生物。:)
当我试图编译它时,我得到了以下错误:构造函数生物在类生物不能应用于给定的类型。人类和生物构造函数中的参数是相同的。那么,问题出在哪里呢?
我还尝试了这个:
人类:
public class Human extends Creature
{
protected int maximumHealthPoints = 100;
protected int maximumSpeed = 4;
} // end Human但没有成功。
现在我得到了这个错误:“字段隐藏了另一个字段”。
我能做些什么来让它正常工作吗?
提前谢谢你,
卢卡斯
发布于 2011-10-20 00:47:22
问题与最大速度或健康点位无关-它是构造函数。您的Creature类只有一个构造函数,它接受一个String。您没有指定如何链接来自Human的超类构造函数,因此编译器正在寻找一个可访问的无参数构造函数。构造函数总是必须链接到超类构造函数或同一类中的另一个构造函数。如果您没有使用super(...)或this(...)指定要链接到的任何内容,那么这相当于:
super();..。这在这种情况下是无效的,因为没有这样的构造函数可以链接到。
您需要:
// You should consider renaming ID to id, by the way...
public Human(String ID)
{
super(ID);
// Other stuff (but don't bother setting the ID field -
// it's already been set by the Creature constructor)
}我还强烈建议您将字段设置为私有,并且仅从Creature中声明的getter/setter方法访问它们。
请注意,与您的标题相反,这里根本没有重写。构造函数不会被重写,只有方法才会被重写。每个类都有自己的构造函数签名集;它们根本不是继承的-它们只是让您从子类链接到超类。
发布于 2011-10-20 00:47:03
更改Human构造函数以调用正确的基类构造函数,如下所示:
public Human(String ID)
{
super(ID);
setMaximumHealthPoints(100);
setMaximumSpeed(4);
}您的代码隐式地尝试调用Creature的无参数构造函数,但该构造函数并不存在。
发布于 2011-10-20 00:57:23
必须在定义默认的非参数构造函数时隐式调用父类的参数构造函数,或者在定义带参数的自定义构造函数时显式调用父类的参数构造函数,如建议的解决方案所示。
https://stackoverflow.com/questions/7824900
复制相似问题