Constructing Objects
Home Up Search Java 2 API C++ Resources

A class definition specifies the characteristics and behaviors of all the objects of that class.   The class definition does not create an object.   In order to create an instance of a class, the constructor of that class must be called.  

The syntax for constructing a new instance of a class is:

new class_name([arg1] [, arg2] [, ...]);

Things to note:

  1. The "new" keyword must be used.  This tells the compiler that a new instance is to be made.
  2. class_name is the name of the class for which you wish to make an instance.   This is the name of the constructor for the class.   A constructor always has the same name as the class.
  3. arg1, arg2, etc are optional arguments to the constructor used to specify an initial state of the object.   As with any method, the types and number of arguments must match one of the constructor signatures in the class definition.

The above syntax creates an object but does not assign it to a variable.   Assigning it to a variable creates a reference to the object that can be used by the rest of the program:

MyClass x = new MyClass();

MyClass y;
y = new MyClass();

A very powerful technique is to use one variable to reference many different objects at different times:

MyClass x;

x = new MyClass();
[ code to process this instance of MyClass goes here]

x= new MyClass();
[ code to process another instance of MyClass goes here]

etc., etc.

Sometimes one doesn't need to assign the new instance to a variable to use it.    One can immediately pass the new object  as an argument of a method that requires an instance of that type of object:

class YourClass
{
    void yourMethod( MyClass x) { [do some stuff] }
}

YourClass y = new YourClass();

y.yourMethod( new MyClass());

The philosophical statement here is that objects exist whether or not they have a name.

In particular, this use of "anonymous" objects is the primary technique used to manage the large numbers of objects generated and used in complex systems.

For information on how to write a constructor, see the page on Methods and Classes.