In the "Terminator condition" section, the author wants to discuss the usage of finalize (), which is a code example. The Code is as follows (comments and test code are omitted ):
Class book ...{
Boolean checkedout = false;
Public book (Boolean checkout )...{
Checkedout = checkout;
}
Public void checkin ()...{
Checkedout = false;
}
Public void finalize ()...{
If (checkedout )...{
System. Out. println ("error: file not checked in ");
}
}
}
Public class terminationcondition ...{
Public static void main (string ARGs [])... {
Book novel = New Book (true)
Novel. checkin ();
New Book (true );
System. GC ();
}
}
The author writes in the book that all book objects should be checked in before being treated as garbage collectors. In the main method, a book is not checked in due to a programmer's error. If finalize () is not used to verify the final condition, it will be difficult to find this error (188th page of Java programming ideology (Third edition)
Let's look at this Code. The author thinks that the program outputs "error: a file is not checked in", so it proves the role of finalize, however, I think it is not appropriate to use this code to prove the author's point of view. We can see that the book novel = New Book (true) Statement in the Code has created an object reference, so whether or not to call checkin (), system. the GC () statement does not collect the object. We can comment out a line of novel. checkin (). During the runtime, we will find that even if there is no checkin, the program still does not output any information.