Java Reference
In-Depth Information
approximation to the value of π, the ratio of the circumference of a circle to its
diameter.
A constant is usually made static because there is no need for more than one
copy of it. Placing one copy of the variable in each instance of a class would
waste space. Making it static means that there is exactly one copy, in the file
drawer of the class. Further, it can be referenced even if no instance of the class
has been created. Just use the class name followed by a period followed by the
constant name, e.g.
Math.PI
.
Providing communication among instances of a class
A bank account generally has an account number. The bank gives each
account a different, unique, number —it would reek havoc on the system to have
two different accounts with the same number.
Consider designing a class
BankAccount
, each instance of which maintains
one bank account, with an owner, account number, and balance. We need a way
to assign a new account number to each instance as it is created. To do this, we
use a static variable
nextAccountNumber
, which always contains the next
account number to generate. We show how the account numbers are created in
Fig. 3.7, which contains part of class
BankAccount
.
/**
An instance is a bank account
*/
public class
BankAccount {
/**
The next account number to assign —numbers
1000..nextAccountNumber-1
have already been assigned
*/
private static int
nextAccountNumber= 1000;
private
String person; //
The account owner
private int
number; //
The account number
private double
balance; //
The balance in the account
/**
Constructor: an account for person
p
with initial balance
b*/
public
BankAccount(String p,
double
b) {
person= p
balance= b;
number= nextAccountNumber;
nextAccountNumber= nextAccountNumber + 1;
}
/** =
the bank account number
*/
public int
getNumber() {
return
number; }
/** = the
number of accounts created thus far
*/
public static int
numberOfAccounts()
{
return
nextAccountNumber - 1000; }
}
Figure 3.7:
Assigning bank account numbers (only three methods are shown)
Search WWH ::
Custom Search