Write a class called MonetaryCoin that is derived from the Coin class presented in Chapter 5. Store an integer in the MonetaryCoin that represents its value and add a method that returns its value. Create a main driver class to instantiate and compute the sum of several MonetaryCoin objects. Demonstrate that a monetary coin inherits its parent’s ability to be flipped.
Below is the Coin Class from Chapter 5:
public class Coin { private final int HEADS = 0; private 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 value. //----------------------------------------------------------------- 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; } }
Expert Answer
Given below is the class for the MoneyCoin and driver. Output shown below. If the answer helped, please don’t forget to rate it. Thank you.
MonetaryCoin.java
public class MonetaryCoin extends Coin {
private int value;
//constructor to initialize a coin’s value
public MonetaryCoin(int val)
{
this.value = val;
}
//method to return the value of this coin
public int getValue()
{
return value;
}
}
MonetaryDriver.java
public class MonetaryDriver {
public static void main(String[] args) {
MonetaryCoin penny = new MonetaryCoin(1); //value of penny is 1
MonetaryCoin nickel = new MonetaryCoin(5); //value of nickel is 5
MonetaryCoin dime = new MonetaryCoin(10); //value of dime is 10
MonetaryCoin quarter = new MonetaryCoin(25); //value of nickel is 25
System.out.println(“Value of penny is ” + penny.getValue());
System.out.println(“Value of nickel is ” + nickel.getValue());
System.out.println(“Value of dime is ” + dime.getValue());
System.out.println(“Value of quarter is ” + quarter.getValue());
//demonstrate that moneytary coin can be flipped
System.out.println(“nickel is now ” + nickel);
nickel.flip();
System.out.println(“nickel is now ” + nickel);
int sum = nickel.getValue() + quarter.getValue();
System.out.println(“Sum of nickel and quarter is ” + sum);
}
}
output
Value of penny is 1
Value of nickel is 5
Value of dime is 10
Value of quarter is 25
nickel is now Heads
nickel is now Tails
Sum of nickel and quarter is 30