KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > junit > samples > money > Money


1 package junit.samples.money;
2
3 /**
4  * A simple Money.
5  *
6  */

7 public class Money implements IMoney {
8
9     private int fAmount;
10     private String JavaDoc fCurrency;
11
12     /**
13      * Constructs a money from the given amount and currency.
14      */

15     public Money(int amount, String JavaDoc currency) {
16         fAmount= amount;
17         fCurrency= currency;
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     public IMoney addMoney(Money m) {
26         if (m.currency().equals(currency()) )
27             return new Money(amount()+m.amount(), currency());
28         return MoneyBag.create(this, m);
29     }
30     public IMoney addMoneyBag(MoneyBag s) {
31         return s.addMoney(this);
32     }
33     public int amount() {
34         return fAmount;
35     }
36     public String JavaDoc currency() {
37         return fCurrency;
38     }
39     public boolean equals(Object JavaDoc anObject) {
40         if (isZero())
41             if (anObject instanceof IMoney)
42                 return ((IMoney)anObject).isZero();
43         if (anObject instanceof Money) {
44             Money aMoney= (Money)anObject;
45             return aMoney.currency().equals(currency())
46                              && amount() == aMoney.amount();
47         }
48         return false;
49     }
50     public int hashCode() {
51         return fCurrency.hashCode()+fAmount;
52     }
53     public boolean isZero() {
54         return amount() == 0;
55     }
56     public IMoney multiply(int factor) {
57         return new Money(amount()*factor, currency());
58     }
59     public IMoney negate() {
60         return new Money(-amount(), currency());
61     }
62     public IMoney subtract(IMoney m) {
63         return add(m.negate());
64     }
65     public String JavaDoc toString() {
66         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
67         buffer.append("["+amount()+" "+currency()+"]");
68         return buffer.toString();
69     }
70     public /*this makes no sense*/ void appendTo(MoneyBag m) {
71         m.appendMoney(this);
72     }
73 }
Popular Tags