task1/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java
author japod@localhost
Sun, 28 Sep 2008 14:12:38 +0200
changeset 6 97662396c0fd
child 16 2864c6d744c0
permissions -rw-r--r--
Adding solutions received for task1
     1 package org.apidesign.apifest08.currency;
     2 
     3 import java.io.Serializable;
     4 import java.math.BigDecimal;
     5 import java.util.Currency;
     6 
     7 /**
     8  * Default implementation of {@link Money} interface. This class is immutable.
     9  * @author lukas
    10  *
    11  */
    12 public final class MoneyImpl implements Serializable, Money{
    13 	private static final long serialVersionUID = -6091808475616516136L;
    14 
    15 	private final BigDecimal amount;
    16 	
    17 	private final Currency currency;
    18 
    19 	public MoneyImpl(BigDecimal amount, Currency currency) {
    20 		if (amount==null) throw new NullPointerException("Amount is null");
    21 		if (currency==null) throw new NullPointerException("Currency is null"+currency);
    22 		this.amount = amount.setScale(2);
    23 		this.currency = currency;
    24 	}
    25 	
    26 	public MoneyImpl(long amount, Currency currency) {
    27 		this(BigDecimal.valueOf(amount), currency);
    28 	}
    29 	
    30 	public MoneyImpl(double amount, Currency currency) {
    31 		this(BigDecimal.valueOf(amount), currency);
    32 	}
    33 
    34 	/* (non-Javadoc)
    35 	 * @see org.apidesign.apifest08.currency.Money#getAmount()
    36 	 */
    37 	public BigDecimal getAmount() {
    38 		return amount;
    39 	}
    40 	
    41 	/* (non-Javadoc)
    42 	 * @see org.apidesign.apifest08.currency.Money#getCurrency()
    43 	 */
    44 	public Currency getCurrency() {
    45 		return currency;
    46 	}
    47 
    48 	@Override
    49 	public int hashCode() {
    50 		final int prime = 31;
    51 		int result = 1;
    52 		result = prime * result + ((amount == null) ? 0 : amount.hashCode());
    53 		result = prime * result
    54 				+ ((currency == null) ? 0 : currency.hashCode());
    55 		return result;
    56 	}
    57 
    58 	@Override
    59 	public boolean equals(Object obj) {
    60 		if (this == obj)
    61 			return true;
    62 		if (obj == null)
    63 			return false;
    64 		if (!(obj instanceof MoneyImpl))
    65 			return false;
    66 		MoneyImpl other = (MoneyImpl) obj;
    67 		if (amount == null) {
    68 			if (other.amount != null)
    69 				return false;
    70 		} else if (!amount.equals(other.amount))
    71 			return false;
    72 		if (currency == null) {
    73 			if (other.currency != null)
    74 				return false;
    75 		} else if (!currency.equals(other.currency))
    76 			return false;
    77 		return true;
    78 	}
    79 	
    80 	@Override
    81 	public String toString() {
    82 		return getClass().getName()+"["+currency+amount+"]";
    83 	}
    84 
    85 	
    86 	
    87 }