/* An instance of this class, which is a child of TossableCoin, ** represents a coin that can be tossed (resulting in either HEADS ** or TAILS). The new functionality here is that a coin is able to ** report how many tosses resulted in HEADS, in TAILS, and in total. */ public class TossableCoinWithCounts extends TossableCoin { // instance variables // ------------------- private int headsCount, tailsCount; // constructor // ----------- public TossableCoinWithCounts() { super(); // call the parent class's constructor. Which is // not necessary, as this call is done by default anyway. // headsCount = 0; // not necessary, as numeric instance variables tailsCount = 0; // are automatically initialized to zero } // observers // ---------- /* Returns the # of times that this coin has been tossed. */ public int numTosses() { return headsCount + tailsCount; } /* Returns the # of times that a toss of this coin resulted in HEADS. ** result of HEADS. */ public int numHeads() { return headsCount; } /* Returns the # of times that a toss of this coin resulted in TAILS. */ public int numTails() { return tailsCount; } @Override public String toString() { return super.toString() + " (# HEADS:" + numHeads() + "; # TAILS:" + numTails() + ")"; } // mutators // -------- @Override // signals that this method overrides an inherited one public void toss() { super.toss(); // invoke the overridden method in parent class if (isHeads()) { headsCount++; } else { tailsCount++; } // Note that because the inherited instance variable (headsShowing) // is declared to be private in the parent class, it cannot be // referred to here. } // --------------------------------------------------------- /* main() method, strictly for testing purposes */ public static void main(String[] args) { TossableCoinWithCounts coin = new TossableCoinWithCounts(); System.out.println("Initially: " + coin); for (int i=0; i != 10; i++) { coin.toss(); System.out.println(coin); } } }