A constructor that normalizes a fraction

The Java class below keeps two private fields and promises that every Fraction object satisfies the invariant written in the comment. Integer division in Java truncates toward zero, and Math.abs returns the absolute value.


Java
public class Fraction {
    private int num;
    private int den;   // invariant: den > 0 and gcd(|num|, den) == 1

    public Fraction(int n, int d) {
        if (d == 0) throw new IllegalArgumentException("zero denominator");
        if (d < 0) { n = -n; d = -d; }
        int g = gcd(Math.abs(n), d);
        num = n / g;
        den = d / g;
    }

    public Fraction times(Fraction other) {
        return new Fraction(num * other.num, den * other.den);
    }

    private static int gcd(int a, int b) {
        while (b != 0) { int t = a % b; a = b; b = t; }
        return a;
    }
}


A client runs these three lines:


Java
Fraction a = new Fraction(6, -8);
Fraction b = new Fraction(-10, -15);
Fraction c = a.times(b);


After these lines run, object a stores numerator and denominator , and object c stores numerator and denominator .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Encapsulation and Information Hiding Questions: