GC (Garbage Collector) calls finalize() when an object at end of scope. Finalize() can be overridden by subclasses to do some other process related cleanup.
|
Finalize Method Example in JAVA
class Students {
int rno;
String student_name;
public Students(int rno,String student_name) {
this.rno = rno;
this.student_name = student_name;
}
public void display(){
System.out.println("RNo :"+rno);
System.out.println("Name :"+student_name);
}
@Override
public void finalize() throws Throwable{
System.out.println("Object going to destroy... ["+rno+","+student_name+"]");
super.finalize();
}
}
class Solution {
public static void main(String args[])throws Exception{
Students stu = new Students(1001,"Sarathy");
stu.display();
// Tells to JVM for running finalize() method at exit
Runtime.runFinalizersOnExit(true);
}
}
|
Output
RNo :1001
Name :Sarathy
Object going to destroy... [1001,Sarathy]
|