You can think of Java classes in much the same way as you think of C structs or Turing records. The most important difference (so far) is that you can also have methods inside classes; these operate on the fields of the object that the methods belong to.
'//' is the comment symbol in Java. All following characters on the same line are ignored by the compiler.
Read the following code carefully, and trace it through in the debugger.
// Fraction: Has two fields, 'numerator' and 'denominator'. Also has a method
// to print itself, and a method to multiply itself by another Fraction.
class Fraction {
public int numerator, denominator;
// Print my numerator and my denominator in the standard "n/d" form.
public void print() {
System.out.println(numerator + "/" + denominator);
}
// Multiply myself by f2.
public void multiply(Fraction f2) {
numerator = numerator * f2.numerator;
denominator = denominator * f2.denominator;
}
}
// FracExample: The class containing the main() method, which manipulates
// Fractions.
class FracExample {
// main: this is where execution starts.
public static void main(String[] pars) {
Fraction f1; // A reference to a Fraction, NOT a Fraction itself.
// The next line creates a new Fraction and makes f1 refer to it.
f1 = new Fraction();
// Initialize what f1 refers to.
f1.numerator = 7;
f1.denominator = 17;
Fraction f2; // A reference to another Fraction.
// THIS NEXT LINE WOULD BE AN ERROR!!! f2 is not a Fraction, only a
// reference to one.
// f2.numerator = 16;
f2 = f1; // Make f2 refer to the same thing that f1 refers to.
// This line changes the numerator to 16. Note that f1's numerator is
// also changed.
f2.numerator = 16;
// This next line prints "16/17".
f1.print();
// This next line prints "16/17", too.
f2.print();
// Create a new Fraction and make f2 point to it. THIS DOES NOT AFFECT
// f1.
f2 = new Fraction();
f2.numerator = 4;
f2.denominator = 5;
// What does this line do?
f1.multiply(f2);
// And what gets printed?
f1.print();
f2.print();
}
}