Next: None. Up: Defining an object. Previous: Using Account.


Constructor methods

Textbook: Section 3.4

When you use the new keyword to create a new object instance, the computer goes through a three-step process.

  1. First it clears out space in memory for holding the data associated with an Account. In this case, this entails making room for the 64 bits associated with the balance field (since balance is a double). If there were other instance variables, space for them would be allocated too.

  2. Then it enters the constructor function for the created object, which initializes the fields of the object (setting balance to be 0.0, in this case).

  3. Finally, it returns the location in memory where Account was placed, so that (in this case) mine can refer to this particular object just created and initialized.

Remember this: The job of a constructor method is to initialize the instance variables of a new instance.. We saw this in our Account definition, where the constructor method sets the initial balance to zero.

Sometimes we want to be able to provide additional data about how to set up a new object. To do this, we can add parameters to our constructor function.

For example, when we create a new account, we might want to initialize it with an initial balance. To do this, we'll have one parameter to our constructor, specifying the initial balance.

public class Account {
    private double balance;

    public Account(double initial) {
        balance = initial;
    }
}
Now, when we create a new account, we have to provide an argument, telling the constructor function what to use for the value of the initial parameter.
Account mine = new Account(1527.21);
This creates for me a new account containing $1,527.21.

Sometimes we might have multiple constructor functions, for different combinations of parameters.

public class Account {
    private double balance;

    public Account() {
        balance = 0.0;
    }
    public Account(double initial) {
        balance = initial;
    }
}
This gives the programmer using the class a choice of ways to create an object. Java will determine which constructor function the programmer has chosen based on the number and types of parameters listed when creating the object.
Account yours = new Account();
Account mine = new Account(1527.21);
In this case, the first line refers to the first constructor function (with no parameters) - it creates your account with an initial balance of $0.00. The second line refers to the second constructor function and creates my account with an initial balance of $1,527.21. Creating multiple constructor methods like this is called overloading the constructor method.

Quiz 1


Next: None. Up: Defining an object. Previous: Constructor methods.