Main Page

Previous Next


When you create an object of a class, a special kind of method called a constructor is always invoked. If you don't define any constructors for your class, the compiler will supply a default constructor in the class that does nothing. The primary purpose of a constructor is to provide you with the means of initializing the instance variables uniquely for the object that is being created. If you are creating a Person object with the name John Doe, then you want to be able to initialize the member holding the person's name to "John Doe". This is precisely what a constructor can do. Any initialization blocks that you have defined in a class are always executed before a constructor.

A constructor has two special characteristics that differentiate it from other class methods:

  • A constructor never returns a value and you must not specify a return type - not even of type void.

  • A constructor always has the same name as the class.

To see a practical example we could add a constructor to our Sphere class definition:

class Sphere {
  static final double PI = 3.14; // Class variable that has a fixed value
  static int count = 0;          // Class variable to count objects

  // Instance variables
  double radius;                 // Radius of a sphere

  double xCenter;                // 3D coordinates
  double yCenter;                // of the center
  double zCenter;                // of a sphere
  // Class constructor
  Sphere(double theRadius, double x, double y, double z) {
    radius = theRadius;         // Set the radius

    // Set the coordinates of the center
    xCenter = x;
    yCenter = y;
    zCenter = z;
    ++count;                    // Update object count

  // Static method to report the number of objects created
  static int getCount() {
    return count;               // Return current object count

  // Instance method to calculate volume
  double volume() {
    return 4.0/3.0*PI*radius*radius*radius;

The definition of the constructor is shaded above. We are accumulating quite a lot of code to define the Sphere class, but as it's just an assembly of the pieces we have been adding, you should find it all quite straightforward.

As you can see, the constructor has the same name as the class and has no return type specified. A constructor can have any number of parameters, including none. The default constructor has no parameters. In our case we have four parameters, and each of the instance variables is initialized with the value of the appropriate parameter. Here is a situation where we might have used the name radius for the parameter, in which case we would need to use the keyword this to refer to the instance variable of the same name. The last action of our constructor is to increment the class variable, count, by 1, so that count accumulates the total number of objects created.

The Default Constructor

If you don't define any constructors for a class, the compiler will supply a default constructor that has no parameters and does nothing. Before we defined a constructor for our Sphere class, the compiler would have supplied one defined like this:

Sphere() {

It has no parameters and has no statements in its body so it does nothing - except enable you to create an object of type Sphere of course. The object created by the default constructor will have fields with their default values set.

Note that if you define a constructor of any kind for a class, the compiler will not supply a default constructor. If you need one - and there are occasions when you do - you must define it explicitly.

Creating Objects of a Class

When you declare a variable of type Sphere with the statement:

Sphere ball;     // Declare a variable

no constructor is called and no object is created. All you have created at this point is the variable ball, which can store a reference to an object of type Sphere, if and when you create one.

Click To expand

You will recall from our discussion of String objects and arrays that the variable and the object it references are distinct entities. To create an object of a class you must use the keyword new followed by a call to a constructor. To initialize ball with an object, you could write:

ball = new Sphere(10.0, 1.0, 1.0, 1.0);   // Create a sphere

Now we have a Sphere object with a radius of 10.0 located at the coordinates (1.0, 1,0, 1.0). The object is created in memory and will occupy a sufficient number of bytes to accommodate all the data necessary to define the object. The variable ball will record where in memory the object is - it acts as a reference to the object.

Of course, you can do the whole thing in one step, with the statement:

Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0);   // Create a sphere

This declares the variable ball and defines the Sphere object to which it refers.

You can create another variable that refers to the same object as ball:

Sphere myBall = ball;

Now the variable myBall refers to the same object as ball. We have only one object still, but we have two different variables that reference it. You could have as many variables as you like referring to the same object.

The separation of the variable and the object has an important effect on how objects are passed to a method, so we need to look at that.

Passing Objects to a Method

When you pass an object as an argument to a method, the mechanism that applies is called pass-by-reference, because a copy of the reference contained in the variable is transferred to the method, not the object itself. The effect of this is shown in the following diagram.

Click To expand

This illustration presumes we have defined a method, changeRadius(), in the class Sphere that will alter the radius value for an object, and that we have a method change() in some other class that calls changeRadius(). When the variable ball is used as an argument to the method change(), the pass-by-reference mechanism causes a copy of ball to be made and stored in s. The variable ball just stores a reference to the Sphere object, and the copy contains that same reference and therefore refers to the same object. No copying of the actual object occurs. This is a major plus in term s of efficiency when passing arguments to a method. Objects can be very complex involving a lot of instance variables. If objects themselves were always copied when passed as arguments, it could be very time consuming and make the code very slow.

Since the copy of ball refers to the same object as the original, when the changeRadius() method is called the original object will be changed. You need to keep this in mind when writing methods that have objects as parameters because this is not always what you want.

In the example shown, the method change() returns the modified object. In practice you would probably want this to be a distinct object, in which case you would need to create a new object from s. You will see how you can write a constructor to do this a little later in this chapter.


Remember that this only applies to objects. If you pass a variable of type int or double to a method for example, a copy of the value is passed. You can modify the value passed as much as you want in the method, but it won't affect the original value.

The Lifetime of an Object

The lifetime of an object is determined by the variable that holds the reference to it - assuming there is only one. If we have the declaration:

Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0);   // Create a sphere

then the Sphere object that the variable ball refers to will die when the variable ball goes out of scope. This will be at the end of the block containing this declaration. Where an instance variable is the only one referencing an object, the object survives as long as the instance variable owning the object survives.


A slight complication can arise with objects though. As you have seen, several variables can reference a single object. In this case the object survives as long as there is still a variable in existence somewhere that references the object.

You can reset a variable to refer to nothing by setting its value to null. If you write the statement:

ball = null;

the variable ball no longer refers to an object, and assuming there is no other object referencing it, the Sphere object it originally referenced will be destroyed. Note that while the object has been discarded, the variable ball still continues to exist. The lifetime of the object is determined by whether any variable anywhere in the program still references it.

The process of disposing of dead objects is called garbage collection. Garbage collection is automatic in Java, but this doesn't necessarily mean that objects disappear from memory straight away. It can be some time after the object becomes inaccessible to your program. This won't affect your program directly in any way. It just means you can't rely on memory occupied by an object that is done with being available immediately. For the most part it doesn't matter; the only circumstances where it might would be if your objects were very large, millions of bytes say, or you were creating and getting rid of very large numbers of objects. In this case you can call the static gc() method defined in the System class to encourage the JVM to do some garbage collecting and recover the memory that the objects occupy:


This is a best efforts deal on the part of the JVM. When the gc() method returns, the JVM will have tried to reclaim the space occupied by discarded objects, but there's no guarantee that it will all be recovered.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor