Add an equals method to the Cash class introduced in this chapter. Two stocks are considered equal if they represent the same amount of cash.
// package inheritance;
public interface Asset {
// how much the asset is worth
public double getMarketValue();
// how much money has been made on this asset
public double getProfit();
}
// package inheritance;
public class Cash implements Asset {
private double amount; // amount of money held
// constructs a cash investment of the given amount
public Cash(double amount) {
this.amount = amount;
}
// returns this cash investment's market value, which
// is equal to the amount of cash
public double getMarketValue() {
return amount;
}
// since cash is a fixed asset, it never has any profit
public double getProfit() {
return 0.0;
}
// sets the amount of cash invested to the given value
public void setAmount(double amount) {
this.amount = amount;
}
// this method overrides the equals method in the Object class
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Cash cash = (Cash) obj;
if (!((Double.valueOf(this.amount)).equals(Double.valueOf(cash.amount)))) {
return false;
}
return true;
}
@Override
public int hashCode() {
// chose a random prime number for better hash functionality
int hash = 31;
hash = 17 * hash + (Double.valueOf(this.amount) != null ? Double.valueOf(this.amount).hashCode() : 0);
return hash;
}
public static void main(String args[]) {
Cash cash = new Cash(452.6);
Cash cash1 = new Cash(685.56);
Cash cash2 = new Cash(543.87);
Cash cash3 = new Cash(685.56);
System.out.println("Are cash and cash2 objects have same values? " + cash.equals(cash2));
System.out.println("Are cash1 and cash3 objects have same values? " + cash1.equals(cash3));
}
}
Output:
Are cash and cash2 objects have same values? false
Are cash1 and cash3 objects have same values? true