Next: None. Up: Defining an object. Previous: Using Account.
Textbook: Section 3.4
When you use the new keyword to create a new object instance, the computer goes through a three-step process.
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.
This creates for me a new account containing $1,527.21.Account mine = new Account(1527.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.
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.Account yours = new Account(); Account mine = new Account(1527.21);
Next: None. Up: Defining an object. Previous: Constructor methods.