/* This file Fraction.java implements a class called Fraction. * Here we implement some simple operations commonly used with fractions, * namely adding, multiplying and reducing. We also have a method that * enables us to print a fraction as a string like "17/20" with the slash. * There are many more things we could implement, such as handling * negative fractions, subtraction, division, reciprocal, mixed numerals, * and another constructor that creates a fraction out of a string as input. */ public class Fraction { // Attributes: numerator and denominator are both integers. private int num; private int denom; // Default Constructor: just make it 1/1 public Fraction() { num = 1; denom = 1; } // Initial value constructor: initialize to a/b public Fraction(int a, int b) { num = a; denom = b; } // Copy constructor: copy num and denom from existing fraction f. public Fraction(Fraction other) { num = other.num; denom = other.denom; } // Operations // toString() allows us to print fractions in the driver. public String toString() { return num + "/" + denom; } // To add fractions, we use the basic formula a/b + c/d = (ad+bc)/bd // But the important thing to notice here is the use of the word "this" // which refers to the fraction object before the . in the function call. // "this" is generally called the receiver object or implicit parameter. public Fraction add(Fraction other) { Fraction sum = new Fraction(); sum.num = this.num * other.denom + this.denom * other.num; sum.denom = this.denom * other.denom; return sum; } // Multiplying fractions is easier than adding them. public Fraction multiply(Fraction other) { Fraction product = new Fraction(); product.num = this.num * other.num; product.denom = this.denom * other.denom; return product; } // Someday, we should implement a "reduceMe()" function. }