Lecture 10: Classes and Objects (II)
We are going to continue from lecture notes 9.
Things to remember:
ClassName.memberReference
objectReference.memberReference
this: an instance method can access the object to which
it belongs
main
method.
Point: distance
main method for test purposes
origin
main method
Fractions and lcm
Fraction that we developed in class today. I am including a complete Unix session in which I:
Test.java
class Fraction inside
Test.java (the source file)
Fraction.class is created (bytecode format)
java Fraction)
main method, execution starts there
toString() method (explained in lecture notes 9)
tucotuco.cs.indiana.edu% vi Test.java
tucotuco.cs.indiana.edu% cat Test.java
class Fraction {
public int num, den;
Fraction (int num, int den) {
this.num = num;
this.den = den;
}
public Fraction add (Fraction anotherFraction) {
return new Fraction(num * anotherFraction.den +
den * anotherFraction.num,
den * anotherFraction.den);
}
public String toString () {
return "(" + num + "/" + den + ") ";
}
public static void main(String[] args) {
Fraction f = new Fraction(1, 3);
Fraction g = new Fraction(1, 2);
Fraction h = f.add(g);
System.out.println( f + " + " + g + " = " + h);
}
}
tucotuco.cs.indiana.edu% ls -l
total 2
-rw-r--r-- 1 dgerman students 598 Feb 11 14:39 Test.java
tucotuco.cs.indiana.edu% javac Test.java
tucotuco.cs.indiana.edu% ls -l
total 6
-rw-r--r-- 1 dgerman students 1180 Feb 11 14:39 Fraction.class
-rw-r--r-- 1 dgerman students 598 Feb 11 14:39 Test.java
tucotuco.cs.indiana.edu% java Fraction
(1/3) + (1/2) = (5/6)
tucotuco.cs.indiana.edu%
Note that den > 0 when I create a new Fraction
Fractions in their lowest terms
gcd to reduce their fractions to their
lowest terms. gcd is explained on page 149 in your textbook.
Try to implement it if you have everything else working in your
Fraction class.