Page 362 - Computer_Science_F5
P. 362
occurs. It is not invoked when an object loses scope, for instance. Consequently, it
is unpredictable when, or even if, finalize() will be executed.
(ii) Finalize() method Chapter Five: Object oriented programming with Java
Program Example 5.22:
FOR ONLINE READING ONLY
Java program to demonstrate finalize()method
public class MyHome {
private int value;
// Constructor
public MyHome(int value) {
this.value = value;
System.out.println(“Object created with value: “ + value);
}
// Destructor-like method
protected void finalize() {
// Cleanup actions
System.out.println(“Object with value “ + value + “ destroyed!”);
}
public static void main(String[] args) {
// Create objects
MyHome obj1 = new MyHome(15);
MyHome obj2 = new MyHome(25);
// Several operations continues
// This set objects 1 and 2 to be null to make it eligible for garbage collection
obj1 = null;
obj2 = null;
// This line of code is going to set garbage collection
System.gc(); // This cod explicitly request garbage collection
System.out.println(“End of program”);
}
}
Output:
Figure 5.21: Demonstrating finalize()method
353
Student’s Book Form Five
Computer Science Form 5.indd 353 23/07/2024 12:34

