What is an object?

Create objects with the new keyword followed by a constructor. For example, the following program creates a TwoDPoint object and prints its fields:

class OriginPrinter {

  public static void main(String[] args) {
    TwoDPoint origin; // only declares, does not allocate
    // The constructor allocates and usually initializes the object
    origin = new TwoDPoint();    
    // set the fields
    origin.x = 0.0;
    origin.y = 0.0;
    // print the two-d point
     "The origin is at " + origin.x + ", " + origin.y);
  }  // end main
} // end OriginPrinter

The . is the member access separator.

A constructor invocation with new is required to allocate an object. There is no C++ like static allocation.

To compile this class, put it in a file called OriginPrinter.java in the same directory as TwoDPoint.java and type:

$ javac OriginPrinter.java

What does this produce?

Is this a complete program now? Can you run it?

Previous | Next | Top | Cafe au Lait

Copyright 1997-2006 Elliotte Rusty Harold
Last Modified August 31, 1998