Computer Science 15-100, Fall 2009
Class Notes:  Getting Started With Writing Classes


// Code from class on why and how we write classes in Java.
// This example simply motivates the discussion.  Next week's
// notes cover the topic in detail.

import java.util.*;

// Driver class.  See the Fraction class below for details.

class GettingStartedWithClasses {
  public static void main(String[] args) {
    Fraction f1 = new Fraction(2,5);
    System.out.println("f1 = " + f1);
    // f1.den = 4;  // do not allow this!
    f1.setDen(4);
    System.out.println("f1 = " + f1);
    System.out.println(f1.equals(new Fraction(1,2)));

    Fraction f2 = new Fraction(2,4);
    System.out.println("f2 = " + f2);

    System.out.println(f1 + " * " + f2 + " = " + f1.times(f2));
    System.out.println(f1 + " + " + f2 + " = " + f1.plus(f2));

    Fraction f3 = new Fraction(3,4);
    Fraction f4 = new Fraction(3,4);
    System.out.println("f3 = " + f3);
    System.out.println("f4 = " + f4);
    System.out.println(f3.equals(f4));
    
    System.out.println(new Fraction(1,2).equals(new Fraction(17,34)));
    
    // Known bugs:
    System.out.println(new Fraction(5,0));
  }
}

class Fraction {
  
  private int num;
  private int den;

  // Fraction f3 = f1.times(f2);
  public Fraction times(Fraction that) {
    // a/b * c/d = ac/bd
    int a = this.num;
    int b = this.den;
    int c = that.num;
    int d = that.den;
    return new Fraction(a*c,b*d);
  }
  
  // Fraction f3 = f1.plus(f2);
  public Fraction plus(Fraction that) {
    // a/b + c/d = ad/bd + bc/bd = (ad+bc)/bd
    int a = this.num;
    int b = this.den;
    int c = that.num;
    int d = that.den;
    return new Fraction(a*d+b*c,b*d);
  }

  private int gcd(int x, int y) {
    // euclid:  gcd(x,y) == gcd(y,x%y)
    while (y > 0) {
      int r = x % y;
      x = y;
      y = r;
    }
    return x;
  }

  public void setDen(int d) {
    this.den = d;
    int gcd = gcd(this.num, this.den);
    this.num = this.num / gcd;
    this.den = this.den / gcd;
  }
  
  
  public Fraction(int n, int d) {
    int gcd = gcd(n, d);
    num = n/gcd;
    den = d/gcd;
  }
  
  public String toString() {
    return num + "/" + den;
  }
  
  public boolean equals(Fraction that) {
    return ((this.num == that.num) && (this.den == that.den));
  }
}

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem