Creating the equals method

Our final method will be one that tests our Fraction class with another Fraction object for equality. Like the toString method, all objects already have a method for this purpose called equals. By default, the equals method returns true if the calling object and the passed in object are physically the same object, meaning that the references to these objects refer to the same object or memory address.

As with the toString method, we'd prefer to implement an equals method which makes a little more sense for our Fraction class. Fractions are considered to be equal if they evaluate to the same value. We could compare the decimalValue of both Fractions, but double comparisons don't always work out as expected. Instead, we can divide both Fractions and see if the result is 1. This is the same as taking the cross-product and comparing the resultant values.

/**
 * Returns whether this Fraction is equal to a given Fraction.
 * Precondition: None
 * Postcondition: None
 * @param other The Fraction to check equality against
 * @return A boolean signifying whether or not this Fraction and the given Fraction are equal
 */
public boolean equals(Fraction secondFraction) {
   if ((this.numerator * secondFraction.denominator) == (this.denominator* secondFraction.numerator))
	return true;

   return false;
}

Testing

  1. Un-comment the code in main that tests whether the two fractions are equal.