Java Reference
In-Depth Information
Static variable nextAccountNumber is initialized to 1000 , the first account
number to use. Look at the constructor. It assigns nextAccountNumber to field
number and increments nextAccountNumber , thus keeping its definition true.
It would be extremely difficult to achieve our goal of having unique account
numbers without using a static field (or at least a static method somewhere, or
adding extra parameters to the constructor), for then there would be no way to
provide communication among the instances of a class. And some form of com-
munication is needed, for how else could we ensure that different accounts have
different account numbers? Using a static variable, the necessary communication
become easy.
In summary, if some form of communication is needed between instances of
a class, consider using static variables.
Style Note
13.1, 13.1.1
naming static
variables
3.3.2
Static methods
In Fig. 3.8, we show class BankAccount 's file drawer, with one folder of the
class as well as the two static components. What can be referenced from, say, the
body of function getNumber in that folder? According to the inside-out rule (see
Sec. 3.1.2), fields person , number , and balance as well as the static components
can be referenced. Indeed, function getNumber references field number . A static
method is also called a class method.
Now look at function numberOfAccounts . Its method body does not refer-
ence any components of instance a1 , so there is no need to place it in the
instance. Therefore, it is made static, so that there is only one copy of it, in the
file drawer. Note that the inside-out rule allows the method body to reference
static variable nextAccountNumber , which it does.
In summary, if a method body does not reference any instance components
of the class in which it is defined, make the method static.
Activity 3-1.3
contains anoth-
er example of
static methods,
dealing with
temperature
conversion.
3.4
Object-oriented design
We discuss the design of a program using classes. It is an idealized design in
which everything is done in a certain order, and correctly. In reality, a design may
require much redoing of earlier steps when something is realized later on. Rarely
can it be done in a completely idealized fashion. Nevertheless, we should strive
for the ideal, for it can reduce the time and effort to complete the program.
3.4.1
The basic idea of OO design
Object-oriented design is the process of designing a program by focusing on the
objects that the program will manipulate and designing the classes that describe
the objects. We do this by focusing on the objects of the problem domain —the
domain for which the program is being written.
Objects are things, so begin by listing objects of the program domain:
Activity
3-8.1
Search WWH ::




Custom Search