我被要求这样做:
设计并实现了一个名为MonetaryCoin的类,该类是从第5章中介绍的硬币类派生出来的。在表示其价值的货币硬币中存储一个值,并为货币价值添加getter和setter方法。
硬币班如下:
public class Coin
{
public final int HEADS = 0;
public final int TAILS = 1;
private int face;
// ---------------------------------------------
// Sets up the coin by flipping it initially.
// ---------------------------------------------
public Coin ()
{
flip();
}
// -----------------------------------------------
// Flips the coin by randomly choosing a face.
// -----------------------------------------------
public void flip()
{
face = (int) (Math.random() * 2);
}
// ---------------------------------------------------------
// Returns true if the current face of the coin is heads.
// ---------------------------------------------------------
public boolean isHeads()
{
return (face == HEADS);
}
// ----------------------------------------------------
// Returns the current face of the coin as a string.
// ----------------------------------------------------
public String toString()
{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
} 我想出了这个:
public class MonetaryCoinHW extends Coin
{
public MonetaryCoinHW(int face)
{
setFace(face);
}
public int getFace()
{
if (isHeads()) {
return HEADS;
}
return TAILS;
}
public void setFace( int newFace )
{
while (newFace != getFace()) {
flip();
}
}不过,我一直有语法错误.我没有正确地使用“超级”吗?我完全糊涂了,我的错误是什么?
发布于 2013-04-24 03:58:01
不,您没有正确地使用super()。
super()调用超级构造函数-在本例中,它将调用继承的Coin()。由于Coin()中不存在用于Coin(int face)的构造函数,所以子类无法调用它。
有办法处理这件事。我相信你需要运行setFace(face)。这将正确地初始化硬币的价值,我认为最适合你的问题。但是,您也可以将Coin(int face)构造函数添加到Coin类中。不过,您还必须给Coin一种保存值的方法。
发布于 2013-04-24 04:04:14
类硬币需要有以下构造函数才能使子类正确工作。
public Coin(int face) {
this.face = face;
}这将解决问题超级(面)。
发布于 2013-04-24 04:06:29
不你打得不对。你需要有硬币的构造函数,只有一个参数是int。即
public Coin (int face)
{
this.face = face;
}https://stackoverflow.com/questions/16183093
复制相似问题