Java Reference
In-Depth Information
}
Purpose:
To define a field that is present in every object of a class
S ELF C HECK
7. Suppose we modify the BankAccount class so that each bank account
has an account number. How does this change affect the instance fields?
8. What are the instance fields of the Rectangle class?
3.5 Implementing Constructors and Methods
Now that we have determined the instance fields, let us complete the BankAccount
class by supplying the bodies of the constructors and methods. Each body contains a
sequence of statements. We'll start with the constructors because they are very
straightforward. A constructor has a simple job: to initialize the instance fields of an
object.
Constructors contain instructions to initialize the instance fields of an object.
Recall that we designed the BankAccount class to have two constructors. The first
constructor simply sets the balance to zero:
public BankAccount()
{
balance = 0;
}
95
96
The second constructor sets the balance to the value supplied as the construction
parameter:
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
To see how these constructors work, let us trace the statement
Search WWH ::




Custom Search