My assignment is this (I have to use inheritance):
Design and implement a class called MonetaryCoin
that is derived from the Coin
class. Store a value in the monetary coin that represents its value and add a method that returns its value. Create a ClientTester
class to instantiate and compute the sum of several different MonetaryCoin
objects. For example Dime, Quarter and HalfDollar have a total value 85 cents.
Coin inherits its parent's ability to be flipped.
My `Coin class is
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;
}
}
My MonetaryCoinClass
is
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;
}
}
And finally my client is
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();
}
}
My Client
is the only one that will not compile. I have no idea what I'm doing for the client. I have to use the flip command I made previously.
Please help me!
Update: My Client is now
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);
}
}
and it compiles. However, how do I make it so that Coin inherits its parent's ability to be flipped?
You should use MonetaryCoin... mc
instead of MonetaryCoin[] mc
, like this:
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
means you will pass in an array, like { m1, m2, m3 }
.MonetaryCoin... mc
means you will pass in an unknown number of MonetaryCoins.