Blocks of code in Java

Source: Internet
Author: User

When studying the context cache code, see a class class similar to static{} such code, more puzzled, so Google to the wind and the hero of a blog post, the article about the code block introduction is very comprehensive, the address is as follows cnblogs.com/end/ Archive/2012/12/21/2827549.html, I'm just finishing up my findings here as my own learning record.

Order of initialization of objects

1. First execute the contents of the parent class static block

2. Then go to the content of the static block of the subclass

3, then go to see if the parent class has no non-static code block, if there is a non-static code block to execute the parent class

4, followed by the construction method of the parent class

5, it goes on to see if the subclass has no non-static code block, if there is a non-static code block to execute the subclass.

6, the subclass of non-static code block execution, and then to execute the subclass of the construction method.

In short, the static code block content executes first, then executes the parent class non-static code block and construction method, then executes the subclass non-static code block and constructs the method.

Why wrap a piece of code with {} to form a block of code

1, the static block is executed only when the class is loaded (not instantiated), and can only be executed once throughout the process, and is typically used to initialize static members in the class.

2. Non-static blocks are always executed when instantiating an object (once per instantiation), and non-static blocks are typically used to initialize non-static members in the class.

Blocks of code in Java

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.