2
How does the "finalize" method work in Java? It is called implicitly? Below is a code with this method that I cannot understand. The class EmployeeTest
calls this method, but I don’t 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());
}
}
Exit from the program:
Employees before instantiation: 0 Employee constructor: Susan Baker; Count = 1 Employee constructor: Bob Blue; Count = 2
Employees after instantiation: via E1.getCount(): 2 routes 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 SUCCESSFULLY BUILT (time total: 0 seconds)
Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.
– Maniero