How does the "finalize" method work in Java? Is it called implicitly? Below is a code with this method that I can not understand. The class EmployeeTest
calls this method, but I do not know how.
package employee;
public class Employee{
private String firstName;
private String lastName;
public static int count = 0;
public Employee (String first, String last) {
firstName = first;
lastName = last;
count++;
System.out.printf("Employee constructor: %s %s; count = %d\n",
firstName,lastName,count);
}
protected void finalize(){
count--;
System.out.printf("Employee finalizer: %s %s ; count = %d\n",
firstName,lastName,count);
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public static int getCount(){
return count;
}
}
package employee;
public class EmployeeTest{
public static void main(String args[]){
System.out.printf("Employees before instantiation: %d\n",
Employee.getCount());
Employee e1 = new Employee("Susan","Baker");
Employee e2 = new Employee ("Bob","Blue");
System.out.println("\nEmployees after instantiation: ");
System.out.printf("via e1.getCount(): %d\n",e1.getCount());
System.out.printf("via e2.getCount(): %d\n",e2.getCount());
System.out.printf("via Employee.getCount(): %d\n",
Employee.getCount());
System.out.printf("\nEmployee 1: %s %s\nEmployee 2: %s %s",
e1.getFirstName(),e1.getLastName(),
e2.getFirstName(),e2.getLastName());
// objetos marcados para a coleta de lixo, pois não são mais referenciados.
e1 = null;
e2 = null;
System.gc();
System.out.printf("\nEmployees afters System.gc():",
Employee.getCount());
}
}
Program exit:
Employees before instantiation: 0 Employee builder: Susan Baker; count = 1 Employee builder: Bob Blue; count = 2
Employees after instantiation: via e1.getCount (): 2 via e2.getCount (): 2 via Employee.getCount (): 2
Employee 1: Susan Baker Employee 2: Bob Blue Employees afters System.gc (): Employee finalizer: Bob Blue; count = 1 Employee finalizer: Susan Baker; count = 0 BUILT WITH SUCCESS (time total: 0 seconds)