task1/solution02/src/org/apidesign/apifest08/currency/MoneyImpl.java
author japod@localhost
Tue, 30 Sep 2008 11:47:02 +0200
changeset 16 2864c6d744c0
parent 6 97662396c0fd
permissions -rw-r--r--
solution 02 updated to 1.5
     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;
    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 	/**
    35 	 * Returns amount.
    36 	 * @return
    37 	 */
    38 	public BigDecimal getAmount() {
    39 		return amount;
    40 	}
    41 	
    42 	/**
    43 	 * Returns currency.
    44 	 */
    45 	public Currency getCurrency() {
    46 		return currency;
    47 	}
    48 
    49 	@Override
    50 	public int hashCode() {
    51 		final int prime = 31;
    52 		int result = 1;
    53 		result = prime * result + ((amount == null) ? 0 : amount.hashCode());
    54 		result = prime * result
    55 				+ ((currency == null) ? 0 : currency.hashCode());
    56 		return result;
    57 	}
    58 
    59 	@Override
    60 	public boolean equals(Object obj) {
    61 		if (this == obj)
    62 			return true;
    63 		if (obj == null)
    64 			return false;
    65 		if (!(obj instanceof MoneyImpl))
    66 			return false;
    67 		MoneyImpl other = (MoneyImpl) obj;
    68 		if (amount == null) {
    69 			if (other.amount != null)
    70 				return false;
    71 		} else if (amount.compareTo(other.amount)!=0)
    72 			return false;
    73 		if (currency == null) {
    74 			if (other.currency != null)
    75 				return false;
    76 		} else if (!currency.equals(other.currency))
    77 			return false;
    78 		return true;
    79 	}
    80 	
    81 	@Override
    82 	public String toString() {
    83 		return getClass().getName()+"["+currency+amount+"]";
    84 	}
    85 
    86 	
    87 	
    88 }