Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes:  Writing Classes (Day 1:  A Gentle Introduction)


Logistics

  1. Schedule
    1. hw8b due tomorrow
    2. quiz7 on Tuesday
  2. Reading:
    1. Ch 4:  Writing Classes

Topic Outline:

  1. Introduction to Writing Classes
public class FractionExample {

    public static java.util.Scanner scanner = new java.util.Scanner(System.in);
    public static java.util.Random random = new java.util.Random();

    public static void main(String[] args) {
      System.out.println(new Fraction(35,49));
      Fraction x = new Fraction(2,7);
      Fraction y = new Fraction(3,7);
      System.out.println("x = " + x);
      System.out.println("y = " + y);
      Fraction z = x.times(y);
      System.out.println("z = " + z);
      System.out.println(x + " + " + y + " = " + x.plus(y));
      for (int p=0; p<5; p++)
        System.out.println(x + "^" + p + " = " + x.pow(p));
    }    
}

class Fraction {
  // instance properties
  // instance == object
  // properties == variables == fields == attributes
  public int num, den;
  
  public static int gcd(int i1, int i2) {
    int gcd = 1;
    for (int i=2; i<=Math.min(i1,i2); i++)
      if ((i1 % i == 0) && (i2 % i == 0)) gcd = i;
    return gcd;
  }
  
  public Fraction(int n, int d) {
    // System.out.println("make a fraction with n = " + n + " and d = " + d);
    int gcd = gcd(n,d);
    num = n / gcd;
    den = d / gcd;
    
  }

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

  public Fraction times(Fraction that) {
    int n = this.num * that.num;
    int d = this.den * that.den;
    return new Fraction(n,d);
  }
  
  public Fraction pow(int p) {
    int n = 1;
    int d = 1;
    for (int power=1; power<=p; power++) {
      n *= this.num;
      d *= this.den;
    }
    return new Fraction(n,d);
  }

  public String toString() {
    return "" + num + "/" + den;
  }
}

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