Java Reference
In-Depth Information
Good Programming Practice 8.1
Invoke every
static
method by using the class name and a dot (
.
) to emphasize that the
method being called is a
static
method.
Class
EmployeeTest
EmployeeTest
method
main
(Fig. 8.13) instantiates two
Employee
objects (lines 13-14).
When each
Employee
object's constructor is invoked, lines 15-16 of Fig. 8.12 assign the
Employee
's first name and last name to instance variables
firstName
and
lastName
. These
two statements do
not
make copies of the original
String
arguments. Actually,
String
ob-
jects in Java are
immutable
—they cannot be modified after they're created. Therefore, it's
safe to have
many
references to one
String
object. This is not normally the case for objects
of most other classes in Java. If
String
objects are immutable, you might wonder why
we're able to use operators
+
and
+=
to concatenate
String
objects. String-concatenation
actually results in a
new
String
object containing the concatenated values. The original
String
objects are
not
modified.
1
// Fig. 8.13: EmployeeTest.java
2
// static member demonstration.
3
4
public class
EmployeeTest
5
{
6
public static void
main(String[] args)
7
{
8
// show that count is 0 before creating Employees
9
System.out.printf(
"Employees before instantiation: %d%n"
,
10
Employee.getCount()
);
11
12
// create two Employees; count should be 2
13
Employee e1 =
new
Employee(
"Susan"
,
"Baker"
);
Employee e2 =
new
Employee(
"Bob"
,
"Blue"
);
14
15
16
// show that count is 2 after creating two Employees
17
System.out.printf(
"%nEmployees after instantiation:%n"
);
18
System.out.printf(
"via e1.getCount(): %d%n"
,
e1.getCount()
e2.getCount()
);
19
System.out.printf(
"via e2.getCount(): %d%n"
,
);
20
System.out.printf(
"via Employee.getCount(): %d%n"
,
21
Employee.getCount()
);
22
23
// get names of Employees
24
System.out.printf(
"%nEmployee 1: %s %s%nEmployee 2: %s %s%n"
,
25
e1.getFirstName(), e1.getLastName(),
26
e2.getFirstName(), e2.getLastName());
27
}
28
}
// end class EmployeeTest
Employees before instantiation: 0
Employee constructor: Susan Baker; count = 1
Employee constructor: Bob Blue; count = 2
Fig. 8.13
|
static
member demonstration. (Part 1 of 2.)