Computer Science 15-100, Spring 2009
Class Notes: Getting Started with Classes
This week we did not follow a formal outline. Instead, we motivated the idea behind classes, objects, and object-oriented programming by interactively designing the following two classes: Point and Fraction.
// The Point class
// Today in class we evolved code from a traditional non-object-oriented
approach to an object-oriented approach. Here is the code as it stood by
the end of class:
// Demonstrates the use of our new "Point" class.
class ClassDemo {
public static void main(String[] args) {
Point point = new Point(5,7); // create a new Point instance (object)
System.out.println(point); // print it out, using its toString method
int dx = 3;
int dy = -8;
point.move(dx, dy); // change (mutate) it, using its move method
System.out.println(point); // and print it out again
}
}
class Point {
// properties (fields)
private int x, y;
// constructor (initializer)
// public void Constructor(...)
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
// accessors ("getters")
public int getX() { return x; }
public int getY() { return y; }
// mutators ("setters")
public void setX(int newX) { x = newX; }
public void setY(int newY) { y = newY; }
public void move(int dx, int dy) {
setX(x + dx);
setY(y + dy);
}
// toString
public String toString() {
return "(" + x + "," + y + ")";
}
}
// The Fraction class
// Today in class we continued to explore creating our own class. Here is
the code as it stood by the end of class:
class FractionDemo {
public static void main(String[] args) {
Fraction f1 = new Fraction(1,2); // 1/2
Fraction f2 = new Fraction(2,6); // 1/3
Fraction f3 = f1.times(f2); // wanted: f3 = f1 * f2;
System.out.println(f1 + " * " + f2 + " = " + f3);
Fraction f4 = new Fraction(1,6); // 1/6
System.out.println(f4);
assert(f3.equals(f4)); // wanted: f3 == f4
}
}
class Fraction {
private int num, den; // numerator and denominator
// a/b * c/d == (ac)/(bd)
public Fraction times(Fraction that) {
return new Fraction(this.num * that.num, this.den * that.den);
}
// public void Constructor(int n, int d)
public Fraction(int n, int d) {
int gcd = gcd(n, d);
num = n/gcd;
den = d/gcd;
}
// @TODO: does not work for negatives, maybe not for 0...
private int gcd(int x, int y) {
if ((x == 0) || (y == 0)) return 1;
if (x < 0) x = -x;
if (y < 0) y = -y;
while (y > 0) {
int r = x % y;
x = y;
y = r;
}
return x;
}
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