Multiple Objects

In general there will be more than one object in any given class. Reference variables are used to distinguish between different objects of the same class.

For example, the following program creates two two-d point objects and prints their fields:

class TwoPointPrinter {
  public static void main(String[] args) {
    TwoDPoint origin; // only declares, does not allocate
    TwoDPoint one; // only declares, does not allocate
    // The constructor allocates and usually initializes the object
    origin = new TwoDPoint();    
    one = new TwoDPoint();
    // set the fields
    origin.x = 0.0;
    origin.y = 0.0;
    one.x = 1.0;
    one.y = 0.0;
    // print the 2D points
     "The origin is at " + origin.x + ", " + origin.y);
    System.out.println("One is at " + one.x + ", " + one.y);
  }  // end main
} // end TwoPointPrinter

one and origin are two different reference variables pointing to two different point objects. It's not enough to identify a variable as a member of a class like x or y in the example above. You have to specify which object in the class you're referring to.

Previous | Next | Top | Cafe au Lait

Copyright 1997-2006 Elliotte Rusty Harold
Last Modified September 18, 2006