Java Reference
In-Depth Information
It makes no sense, though, to make this value into an instance field:
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
private int lastAssignedNumber = 1000; // NOȌwonȐt
work
}
In that case each instance of the BankAccount class would have its own value of
1astAssignedNumber .
Instead, we need to have a single value of lastAssignedNumber that is the same
for the entire class. Such a field is called a static field, because you declare it using
the static keyword.
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 1000;
}
Every BankAccount object has its own balance and accountNumber instance
fields, but there is only a single copy of the lastAssignedNumber variable (see
Figure 4 ). That field is stored in a separate location, outside any BankAccount
objects.
A static field belongs to the class, not to any object of the class.
A static field is sometimes called a class field because there is a single field for the
entire class.
Every method of a class can access its static fields. Here is the constructor of the
BankAccount class, which increments the last assigned number and then uses it to
initialize the account number of the object to be constructed:
public class BankAccount
Search WWH ::




Custom Search