Java Reference
In-Depth Information
variable is initialized to zero in line 7. If a static variable is not initialized, the compiler
assigns it a default value—in this case 0 , the default value for type int .
1
// Fig. 8.12: Employee.java
2
// static variable used to maintain a count of the number of
3
// Employee objects in memory.
4
5
public class Employee
6
{
7
private static int count = 0 ; // number of Employees created
8
private String firstName;
9
private String lastName;
10
11
// initialize Employee, add 1 to static count and
12
// output String indicating that constructor was called
13
public Employee(String firstName, String lastName)
14
{
15
this .firstName = firstName;
16
this .lastName = lastName;
17
18
++count; // increment static count of employees
19
System.out.printf( "Employee constructor: %s %s; count = %d%n" ,
20
firstName, lastName, count);
21
}
22
23
// get first name
24
public String getFirstName()
25
{
26
return firstName;
27
}
28
29
// get last name
30
public String getLastName()
31
{
32
return lastName;
33
}
34
35
// static method to get static count value
public static int getCount()
{
return count;
}
36
37
38
39
40
} // end class Employee
Fig. 8.12 | static variable used to maintain a count of the number of Employee objects in
memory.
When Employee objects exist, variable count can be used in any method of an
Employee object—this example increments count in the constructor (line 18). The public
static method getCount (lines 36-39) returns the number of Employee objects that have
been created so far. When no objects of class Employee exist, client code can access variable
count by calling method getCount via the class name, as in Employee.getCount() . When
objects exist, method getCount can also be called via any reference to an Employee object.
Search WWH ::




Custom Search