The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Constructors

The usual role of a constructor is to initialize the instance variables. The syntax for constructors is similar to that of other methods, with three exceptions:

  • The name of the constructor is the same as the name of the class.
  • Constructors have no return type and no return value.
  • The keyword static is omitted.

Here is an example for the Time class:

  public Time () {
    this.hour = 0;
    this.minute = 0;
    this.second = 0.0;
  }

Notice that where you would expect to see a return type, between public and Time, there is nothing. That's how we (and the compiler) can tell that this is a constructor.

This constructor does not take any arguments, as indicated by the empty parentheses (). Each line of the constructor initializes an instance variable to an arbitrary default value (in this case, midnight). The name this is a special keyword that is the name of the object we are creating. You can use this the same way you use the name of any other object. For example, you can read and write the instance variables of this, and you can pass this as an argument to other methods.

But you do not declare this and you do not use new to create it. In fact, you are not even allowed to make an assignment to it! this is created by the system; all you have to do is store values in its instance variables.

A common error when writing constructors is to put a return statement at the end. Resist the temptation.



Last Update: 2011-01-24