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.


Creating a New Object

Although constructors look like methods, you never invoke them directly. Instead, when you use the new command, the system allocates space for the new object and then invokes your constructor to initialize the instance variables.

The following program demonstrates two ways to create and initialize Time objects:

class Time {
  int hour, minute;
  double second;

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

  public Time (int hour, int minute, double second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }

  public static void main (String[] args) {

    // one way to create and initialize a Time object
    Time t1 = new Time ();
    t1.hour = 11;
    t1.minute = 8;
    t1.second = 3.14159;
    System.out.println (t1);

    // another way to do the same thing
    Time t2 = new Time (11, 8, 3.14159);
    System.out.println (t2);
  }
}

As an exercise, figure out the flow of execution through this program.

In main, the first time we invoke the new command, we provide no arguments, so Java invokes the first constructor. The next few lines assign values to each of the instance variables.

The second time we invoke the new command, we provide arguments that match the parameters of the second constructor. This way of initializing the instance variables is more concise (and slightly more efficient), but it can be harder to read, since it is not as clear which values are assigned to which instance variables.



Last Update: 2011-01-24