Tracking the Number of Employee Objects That Have Been Created
Our next program declares two classes—Employee
(Fig. 8.12) and EmployeeTest
(Fig. 8.13). Class Employee
declares private static
variable count
(Fig. 8.12, line 9) and public static
method getCount
(lines 36–39). The static
variable count
is initialized to zero in line 9. If a static
variable is not initialized, the compiler assigns it a default value—in this case 0
, the default value for type int
. Variable count
maintains a count of the number of objects of class Employee
that have been created so far.
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
Get Java How to Program (early objects), 9/e now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.