我的任务是这样(我必须使用继承):
设计并实现一个称为MonetaryCoin
的类,该类是从Coin
类派生的。将一个值存储在代表其值的货币硬币中,并添加一个返回其值的方法。创建一个ClientTester
类来实例化和计算几个不同的MonetaryCoin
对象的总和。例如,Dime,Quarter和HalfDollar的总价值为85美分。
硬币继承了其父母被翻转的能力。
我的硬币班是
import java.util.Random;
public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
// Constructor... sets up the coin by flipping it initially
public Coin()
{
flip();
}
// flips the coin by randomly choosing a face value
public void flip()
{
face = (int)(Math.random()*2); //random numbers 0 or 1
}
// returns true if the current face of the coin is head
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;
}
}
我的
MonetaryCoinClass
是public class MonetaryCoin extends Coin
{
private int value;
public MonetaryCoin( int value )
{
this.value = value;
}
public int getValue()
{
return this.value;
}
public void setValue( int value )
{
this.value = value;
}
public int add( MonetaryCoin [] mc )
{
if ( mc.length >= 0 )
return -1;
int total = this.value;
for ( int i = 0; i < mc.length; i++ )
{
total += mc[i].getValue();
}
return total;
}
}
最后我的客户是
public class Client
{
public static void main()
{
MonetaryCoin mc1 = new MonetaryCoin( 25 );
MonetaryCoin mc2 = new MonetaryCoin( 13 );
MonetaryCoin mc3 = new MonetaryCoin( 33 );
int total = mc1.add( mc2, mc3 );
int value = mc2.getValue();
}
}
我的
Client
是唯一不会编译的。我不知道我要为客户做什么。我必须使用之前制作的flip命令。请帮我!
更新:我的客户现在
public class Client
{
public static void main()
{
MonetaryCoin mc1 = new MonetaryCoin( 25 );
MonetaryCoin mc2 = new MonetaryCoin( 13 );
MonetaryCoin mc3 = new MonetaryCoin( 33 );
MonetaryCoin[] test = new MonetaryCoin[2];
test[0] = mc2;
test[1] = mc3;
int total = mc1.add(test);
int value = mc2.getValue();
System.out.println("total: " +total+ " values: " +value);
}
}
并编译。但是,如何使硬币继承其父代的翻转能力呢?
最佳答案
您应使用MonetaryCoin... mc
而不是MonetaryCoin[] mc
,如下所示:
public class MonetaryCoin extends Coin{
// All your other methods
// ...
public int add(MonetaryCoin... mc)
{
if ( mc.length >= 0 )
return -1;
int total = this.value;
for ( int i = 0; i < mc.length; i++ )
{
total += mc[i].getValue();
}
return total;
}
}
MonetaryCoin[] mc
表示您将传入一个数组,例如{ m1, m2, m3 }
。MonetaryCoin... mc
表示您将传入未知数量的MonetaryCoins。关于java - 货币硬币继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34325303/