Skip to main content
Engineering LibreTexts

2.2: Constructors

  • Page ID
    15278
  • After declaring the instance variables, the next step is to define a constructor, which is a special method that initializes the instance variables. The syntax for constructors is similar to that of other methods, except:

    • 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 constructor for the Time class:

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

    This constructor does not take any arguments. Each line initializes an instance variable to zero (which in this example means midnight).

    The name this is a keyword that refers to 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 can’t make an assignment to it.

    A common error when writing constructors is to put a return statement at the end. Like void methods, constructors do not return values.

    To create a Time object, you must use the new operator:

    Time time = new Time();
    

    When you invoke new, Java creates the object and calls your constructor to initialize the instance variables. When the constructor is done, new returns a reference to the new object. In this example, the reference gets assigned to the variable time, which has type Time. Figure 11.2.1 shows the result.

    State diagram of a Time object.
    Figure \(\PageIndex{1}\): State diagram of a Time object.

    Beginners sometimes make the mistake of invoking new inside the constructor. You don’t have to, and you shouldn’t. In this example, invoking new Time() in the constructor causes an infinite recursion:

    public Time() {
        new Time();        // wrong!
        this.hour = 0;
        this.minute = 0;
        this.second = 0.0;
    }