By Doug Lowe

A constructor is a block of code that’s called when an instance of an object is created in Java. In many ways, a constructor is similar to a method, but a few differences exist:

  • A constructor doesn’t have a return type.

  • The name of the constructor must be the same as the name of the class.

  • Unlike methods, constructors are not considered to be members of a class. (That’s important only when it comes to inheritance.)

  • A constructor is called when a new instance of an object is created. In fact, it’s the new keyword that calls the constructor. After creating the object, you can’t call the constructor again.

Here’s the basic format for coding a constructor:

public ClassName (parameter-list) [throws exception...]
{
 statements...
}

The public keyword indicates that other classes can access the constructor. That’s usually what you want, although you might want to create a private constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method.

Notice also that a constructor can throw exceptions if it encounters situations that it can’t recover from.

Creating basic constructors

Probably the most common reason for coding a constructor is to provide initial values for class fields when you create the object. Suppose that you have a class named Actor that has fields named firstName and lastName. You can create a constructor for the Actor class:

public Actor(String first, String last)
{
 firstName = first;
 lastName = last;
}

Then you create an instance of the Actor class by calling this constructor:

Actor a = new Actor("Arnold", "Schwarzenegger");

A new Actor object for Arnold Schwarzenegger is created.

Like methods, constructors can be overloaded. In other words, you can provide more than one constructor for a class, provided that each constructor has a unique signature. Here’s another constructor for the Actor class:

public Actor(String first, String last, boolean good)
{
 firstName = first;
 lastName = last;
 goodActor = good;
}

This constructor lets you create an Actor object with information besides the actor’s name:

Actor a = new Actor("Arnold", "Schwarzenegger", false);

Creating default constructors

Every class has a right to a constructor. If you don’t provide a constructor, Java appoints one for you, free of charge. This free constructor is called the default constructor. It doesn’t accept any parameters and doesn’t do anything, but it does allow your class to be instantiated.

Thus, the following two classes are identical:

public Class1
{
 public Class1() { }
}
public Class1 { }

In the first example, the class explicitly declares a constructor that doesn’t accept any parameters and has no statements in its body. In the second example, Java creates a default constructor that works just like the constructor shown in the first example.

The default constructor is not created if you declare any constructors for the class. As a result, if you declare a constructor that accepts parameters and still want to have an empty constructor (with no parameters and no body), you must explicitly declare an empty constructor for the class.

An example might clear this point up. The following code does not compile:

public class BadActorApp
{
 public static void main(String[] args)
 {
  Actor a = new Actor(); // error: won’t compile
 }
}
class Actor
{
 private String lastName;
 private String firstName;
 private boolean goodActor;
 public Actor(String last, String first)
 {
  lastName = last;
  firstName = first;
 }
 public Actor(String last, String first, boolean good)
 {
  lastName = last;
  firstName = first;
  goodActor = good;
 }
}

This program won’t compile because it doesn’t explicitly provide a default constructor for the Actor class; because it does provide other constructors, the default constructor isn’t generated automatically.

Calling other constructors

A constructor can call another constructor of the same class by using the special keyword this as a method call. This technique is commonly used when you have several constructors that build on one another.

Consider this class:

public class Actor
{
 private String lastName;
 private String firstName;
 private boolean goodActor;
 public Actor(String last, String first)
 {
  lastName = last;
  firstName = first;
 }
 public Actor(String last, String first, boolean good)
 {
  this(last, first);
  goodActor = good;
 }
}

Here the second constructor calls the first constructor to set the lastName and firstName fields. Then it sets the goodActor field.

You have a few restrictions in using the this keyword as a constructor call:

  • You can call another constructor only in the very first statement of a constructor. Thus, the following code won’t compile:

     public Actor(String last, String first, boolean good)
     {
      goodActor = good;
      this(last, first);  // error: won’t compile
     }

    If you try to compile a class with this constructor, you get a message saying call to this must be first statement in constructor.

  • Each constructor can call only one other constructor, but you can chain constructors. If a class has three constructors, the first constructor can call the second one, which in turn calls the third one.

  • You can’t create loops in which constructors call one another. Here’s a class that won’t compile:

    class CrazyClass
    {
     private String firstString;
     private String secondString;
     public CrazyClass(String first, String second)
     {
       this(first);
       secondString = second;
     }
     public CrazyClass(String first)
     {
       this(first, "DEFAULT"); // error: won’t
       // compile
     }
    }

    The first constructor starts by calling the second constructor, which calls the first constructor. The compiler complains that this error is a recursive constructor invocation and politely refuses to compile the class.

If you don’t explicitly call a constructor in the first line of a constructor, Java inserts code that automatically calls the default constructor of the base class — that is, the class that this class inherits.