View Javadoc
1   package junit.samples.money;
2   
3   /**
4    * A simple Money.
5    */
6   public class Money implements IMoney {
7   
8       private int fAmount;
9       private String fCurrency;
10  
11      /**
12       * Constructs a money from the given amount and currency.
13       */
14      public Money(int amount, String currency) {
15          fAmount = amount;
16          fCurrency = currency;
17      }
18  
19      /**
20       * Adds a money to this money. Forwards the request to the addMoney helper.
21       */
22      public IMoney add(IMoney m) {
23          return m.addMoney(this);
24      }
25  
26      public IMoney addMoney(Money m) {
27          if (m.currency().equals(currency())) {
28              return new Money(amount() + m.amount(), currency());
29          }
30          return MoneyBag.create(this, m);
31      }
32  
33      public IMoney addMoneyBag(MoneyBag s) {
34          return s.addMoney(this);
35      }
36  
37      public int amount() {
38          return fAmount;
39      }
40  
41      public String currency() {
42          return fCurrency;
43      }
44  
45      @Override
46      public boolean equals(Object anObject) {
47          if (isZero()) {
48              if (anObject instanceof IMoney) {
49                  return ((IMoney) anObject).isZero();
50              }
51          }
52          if (anObject instanceof Money) {
53              Money aMoney = (Money) anObject;
54              return aMoney.currency().equals(currency())
55                      && amount() == aMoney.amount();
56          }
57          return false;
58      }
59  
60      @Override
61      public int hashCode() {
62          if (fAmount == 0) {
63              return 0;
64          }
65          return fCurrency.hashCode() + fAmount;
66      }
67  
68      public boolean isZero() {
69          return amount() == 0;
70      }
71  
72      public IMoney multiply(int factor) {
73          return new Money(amount() * factor, currency());
74      }
75  
76      public IMoney negate() {
77          return new Money(-amount(), currency());
78      }
79  
80      public IMoney subtract(IMoney m) {
81          return add(m.negate());
82      }
83  
84      @Override
85      public String toString() {
86          return "[" + amount() + " " + currency() + "]";
87      }
88  
89      public /*this makes no sense*/ void appendTo(MoneyBag m) {
90          m.appendMoney(this);
91      }
92  }