430 Object-Based Programming Chapter 8 6 public class (Web servers)

430 Object-Based Programming Chapter 8 6 public class EmployeeTest { 7 8 // test class Employee 9 public static void main( String args[] ) 10 { 11 // prove that count is 0 before creating Employees 12 String output = “Employees before instantiation: ” + 13 Employee.getCount(); 14 15 // create two Employees; count should be 2 16 Employee e1 = new Employee( “Susan”, “Baker” ); 17 Employee e2 = new Employee( “Bob”, “Jones” ); 18 19 // Prove that count is 2 after creating two Employees. 20 // Note: static methods should be called only via the 21 // class name for the class in which they are defined. 22 output += “nnEmployees after instantiation: ” + 23 “nvia e1.getCount(): ” + e1.getCount() + 24 “nvia e2.getCount(): ” + e2.getCount() + 25 “nvia Employee.getCount(): ” + Employee.getCount(); 26 27 // get names of Employees 28 output += “nnEmployee 1: ” + e1.getFirstName() + 29 ” ” + e1.getLastName() + “nEmployee 2: ” + 30 e2.getFirstName() + ” ” + e2.getLastName(); 31 32 // If there is only one reference to each employee (as 33 // on this example), the following statements mark 34 // those objects for garbage collection. Otherwise, 35 // these statement simply decrement the reference count 36 // for each object. 37 e1 = null; 38 e2 = null; 39 40 System.gc(); // suggest call to garbage collector 41 42 // Show Employee count after calling garbage collector. 43 // Count displayed may be 0, 1 or 2 depending on 44 // whether garbage collector executed immediately and 45 // number of Employee objects it collects. 46 output += “nnEmployees after System.gc(): ” + 47 Employee.getCount(); 48 49 JOptionPane.showMessageDialog( null, output, 50 “Static Members and Garbage Collection”, 51 JOptionPane.INFORMATION_MESSAGE ); 52 53 System.exit( 0 ); 54 } 55 56 } // end class EmployeeTest Fig. 8.21 Using a staticclass variable to maintain a count of the number of objects of a class (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply