Java Reference
In-Depth Information
Next, you need to supply constructors. We will want to construct bank accounts that
initially have a zero balance, by using the default constructor:
BankAccount harrysChecking = new BankAccount();
What if a programmer who uses our class wants to start out with another balance? A
second constructor that sets the balance to an initial value will be useful:
BankAccount momsSavings = new BankAccount(5000);
To summarize, it is specified that two constructors will be provided:
ȗ public BankAccount()
ȗ public BankAccount(double initialBalance)
A constructor is very similar to a method, with two important differences.
ȗ The name of the constructor is always the same as the name of the class (e.g.,
BankAccount )
ȗ Constructors have no return type (not even void )
Just like a method, a constructor also has a bodyȌa sequence of statements that is
executed when a new object is constructed.
Constructors contain instructions to initialize objects. The constructor name is
always the same as the class name.
public BankAccount()
{
bodyÏfilled in later
}
87
88
The statements in the constructor body will set the internal data of the object that is
being constructedȌsee Section 3.5 .
Don't worry about the fact that there are two constructors with the same nameȌall
constructors of a class have the same name, that is, the name of the class. The
compiler can tell them apart because they take different parameters.
Search WWH ::




Custom Search