The garbage collector only knows how to release memory allocated by new. Once the garbage collector is ready to recycle new objects, it will first call the finalize () method, which can clean up the garbage collection.
This means that if you have to execute some actions before you need an object, you have to perform the finalize () method on your own ). Generally, you cannot expect finalize (). You must create other "Cleanup" methods and call them explicitly. Finalize (): verifies the object "Terminator condition.
Class finalizetest ...{
Public static void main (string [] ARGs )...{
Auto auto = new auto (); // when an object is not referenced, it becomes garbage. The new object in this sentence is not garbage.
Auto = NULL; // The new object is junk.
New auto ();
New auto ();
System. GC ();
}
}
Class auto ...{
Public void finalize ()...{
System. Out. println ("Auto is going ");
}
}
PS: If the finalize () method is placed in the auto class, the new auto () object will be called when it is recycled. If the finalize () method is placed in the finalizetest class, new auto () objects will not be called when they are recycled, and new finalizetest () objects will be called only when they are recycled.
Running result:
Auto is going
Auto is going
Auto is going
Another application instance
Class book ...{
Public Boolean checkedout = false;
Public book (Boolean checkout )...{
Checkedout = checkout;
}
Public void checkin ()...{
Checkedout = false; // status conversion & normalize the checkedout variable to false
}
Public void finalize ()...{
If (checkedout)
System. Out. println ("This book has not executed checkin ");
}
Public static void main (string [] ARGs )...{
Book thinkinginjava = New Book (true );
Thinkinginjava. checkin ();
Book Datastructure = New Book (true );
Datastructure = NULL;
System. GC ();
}
}