Creating the reciprocal method

Another operation that may be useful for our Fraction class is calculating the reciprocal. Instead of altering a Fraction object and changing it into its reciprocal, we will return a new Fraction object.

Make note of the use of accessors rather than directly referring to the instance variables. This is a good programming practice. Note that when taking the reciprocal we are not modifying the current object's numerator and denominator. Rather we are creating a new fraction that will be the reciprocal of the current fraction. After the invocation of reciprocal method, the fraction class on which the method was invoked remains the same.

/**
 * Returns the reciprocal of this Fraction
 * @return A Fraction that is the reciprocal of this Fraction
 */
public Fraction reciprocal()
{
	return new Fraction( getDenominator(), getNumerator() );	
}

Testing

  1. Un-comment the code in main that prints the reciprocals of the two fractions.