Thoughts on a piece of code in Java programming ideology

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.