SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Inheritance And Interfaces
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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

 

0 0

Discussions

Post the discussion to improve the above solution.