1 package junit.samples.money; 2 3 7 public class Money implements IMoney { 8 9 private int fAmount; 10 private String fCurrency; 11 12 15 public Money(int amount, String currency) { 16 fAmount= amount; 17 fCurrency= currency; 18 } 19 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 currency() { 37 return fCurrency; 38 } 39 public boolean equals(Object 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 toString() { 66 StringBuffer buffer = new StringBuffer (); 67 buffer.append("["+amount()+" "+currency()+"]"); 68 return buffer.toString(); 69 } 70 public void appendTo(MoneyBag m) { 71 m.appendMoney(this); 72 } 73 } | Popular Tags |