I'll take it from here:
public boolean equals(Object anObject) {
if (anObject instanceof Money) {
Money aMoney= (Money)anObject;
return aMoney.currency().equals(fCurrency) && aMoney.amount() == fAmount;
}
return false;
}
What you have here is a method.
public boolean equals(Object anObject) {
Declares that this method is publilc, should return a boolean, and takes an Object as an arguement.
if (anObject instanceof Money) {
This line compares the object which is passed in as an argument, to the Class you've created called Money. the call "instanceof" returns true or false, and determines if the Objecct is an Instance of the Money Class.
Money aMoney= (Money)anObject;
This line allocates a portion of memory, and identifies the Object in that space as an object of Class Money. It then takes the object passed into the Method and Casts it to the Money Class. This only occurs if the preceding line (instanceof) returns true. If you did this without the prior check you might get an exception, say if you passed in a String.
return aMoney.currency().equals(fCurrency) && aMoney.amount() == fAmount;
Now that you have an object which is the type Money, you can use methods which are declared in the Money class. These include the method currency()
and amount()
. What you are doing here is retreiving the values for currency in the passed in object to some constant value (fCurrencY) and amount() to some other value (fAmount). You check to determine their equivlance, and return the truth result of ANDing the results of the two comparisons together.
You could rewrite this line as:
boolean currencyEqual = aMoney.currency().equals(fCurrency); // string and or object comparison for equivlance
boolean amount = aMoney.amount() == fAmount; // numeric comparison
boolean bothEqual = currencyEqual && amount; //boolean AND operation (1 && 1 = 1, 1&&0 = 0, 0 && 0 = 0)
return bothEqual;
The final line:
return false;
Only runs if the passed in argument is not an instanceof Money, and thus you return false.
For a very good description of instanceof:
What is the 'instanceof' operator used for?
For a discussion of method declarations:
http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
for inheritance trees and casting:
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html