提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
静态变量,用于维护内存中Employee对象数量的计数
public class Main /**from NowJava.com - 时 代 Java**/ { public static void main(String[] args) { // show that count is 0 before creating Employees System.out.printf("Employees before instantiation: %d%n", Employee.getCount()); // create two Employees; count should be 2 Employee e1 = new Employee("Ana", "Bates"); Employee e2 = new Employee("Mary", "Lady"); // show that count is 2 after creating two Employees System.out.printf("%nEmployees after instantiation:%n"); System.out.printf("via e1.getCount(): %d%n", e1.getCount()); System.out.printf("via e2.getCount(): %d%n", e2.getCount()); /** n o w j a v a . c o m **/ System.out.printf("via Employee.getCount(): %d%n", Employee.getCount()); // get names of Employees System.out.printf("%nEmployee 1: %s %s%nEmployee 2: %s %s%n", e1.getFirstName(), e1.getLastName(), e2.getFirstName(), e2.getLastName()); } } class Employee { private static int count = 0; // number of Employees created private String firstName; private String lastName; // initialize Employee, add 1 to static count and // output String indicating that constructor was called public Employee(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; ++count; // increment static count of employees System.out.printf("Employee constructor: %s %s; count = %d%n", firstName, lastName, count); } // get first name public String getFirstName() {