Static code blocks in Java, Construction code blocks, constructors, ordinary code blocks (reprinted)

Source: Internet
Author: User

Tag: BER does not have to return an IMG action item to start www. Word Proof

Reprinted from: http://www.cnblogs.com/ysocean/p/8194428.html

Directory

    • 1. Static code block
      • ①, format
      • ②, timing of execution
      • The role of ③, static code blocks
      • ④, static code block cannot exist in any method body
      • ⑤, static code blocks cannot access normal variables
    • 2. Building code Blocks
      • ①, format
      • ②, timing of execution
      • The function of ③ and constructing code blocks
    • 3. Constructor function
    • 4, ordinary code block
    • 5. Order of execution
    • 6, parent class and subclass execution order

In Java, the execution order of static blocks of code, construction blocks, constructors, and ordinary blocks of code is a test-taker, which hopefully gives you a thorough understanding of the order of execution between them.

Back to top 1, static block of code

①, format

In a Java class (a static block of code cannot exist in a method) use the static keyword and the code block declared by {}:

12345 publicclassCodeBlock {    static{        System.out.println("静态代码块");    }}

②, timing of execution

Static blocks of code run when the class is loaded, run only once, and take precedence over various blocks of code and constructors. If there is more than one static block of code in a class, it is executed sequentially in the order of writing. The latter will be proved by concrete examples at the time of comparison.

The role of ③, static code blocks

In general, if some code needs to be executed when the project is started, a static block of code is required. For example, when a project launches a lot of resources such as many configuration files that need to be loaded, we can put them into static code blocks.

④, static code block cannot exist in any method body

This should be well understood, first of all we have to make it clear that the static code block is going to run when the class loads. We discuss the situation:

For the normal method, because the normal method is to run this method by loading the class and then new out instantiating the object, the static code block only needs to load the class and then it can run.

For static methods, when the class is loaded, the static method is loaded, but we have to access it through the class name or object name, that is, the static code block is active when compared to the static code block, and the static method is passive.

Either way, we need to make clear that the existence of a static block of code runs automatically when the class is loaded, and is not automatically run in either the normal or static methods.

⑤, static code blocks cannot access normal variables

This understanding of the same thinking, ordinary variables can only be called by the object, is not placed in the static code block.

Back to top 2, building blocks of code

①, format

The block of code declared with {} in the Java class (and the static code block differs by the lack of the static keyword):

12345678 publicclassCodeBlock {    static{        System.out.println("静态代码块");    }    {        System.out.println("构造代码块");    }}

②, timing of execution

The construction code block is called when the object is created, and is called once for each creation of the object, but takes precedence over the constructor execution. It is important to note that by listening to a name, we know that constructing a code block is not a priority over the constructor execution, but rather relies on the constructor, that is, if you do not instantiate the object, the code block is not executed. How do you understand it? Let's take a look at the following code:

123456789101112 publicclassCodeBlock {    {        System.out.println("构造代码块");    }        publicCodeBlock(){        System.out.println("无参构造函数");    }    publicCodeBlock(String str){        System.out.println("有参构造函数");    }}

We decompile the generated class file:

  

If more than one construction code block exists, the order of execution is executed sequentially, in writing order.

The function of ③ and constructing code blocks

Like constructors, you can initialize an object and construct a block of code once the object is created. In turn, however, constructors do not have to be executed every time the object is established (in the case of multiple constructors, the arguments passed in when the object is created are initialized with the corresponding constructor).

The Construction code block feature is invoked once every time the object is created, and we can do things like count the number of times the object was created.

Back to top 3, constructors

1. Constructors must be named exactly the same as the class name. In Java, a normal function can have the same name as a constructor, but must have a return value;

2. The function of the constructor is primarily used to define the state of the initialization when the object of the class is created. It has no return value and cannot be decorated with void. This ensures that not only does it not have to be returned automatically, but there is no choice at all. Other methods have a return value, even if it is a void return value. Although the method body itself does not automatically return anything, it can still be returned to something that may be unsafe;

3. The constructor cannot be called directly, it must be called automatically by the new operator when the object is created, and the general method is called when the program executes to it;

4. When a class is defined, the constructor for that class is usually displayed, and the work of specifying initialization in the function can also be omitted, but the Java compiler provides a default constructor. This default constructor is non-parametric. But the general method does not exist this characteristic;

Back to top 4, normal code block

The difference between a normal code block and a construction code block is that the construction code block is defined in the class, and the normal code block is defined in the method body. And the normal code blocks are executed in the same order as the writing order.

12345 publicvoidsayHello(){    {        System.out.println("普通代码块");    }}
Back to Top 5, order of execution
    •  Static code blocks > construct code blocks > Constructors > Common code blocks 
12345678910111213141516171819202122232425 public classCodeBlock {    static{        System.out.println("静态代码块");    }    {        System.out.println("构造代码块");    }    publicCodeBlock(){        System.out.println("无参构造函数");    }        public voidsayHello(){        {            System.out.println("普通代码块");        }    }        publicstaticvoidmain(String[] args) {        System.out.println("执行了main方法");                newCodeBlock().sayHello();;        System.out.println("---------------");        newCodeBlock().sayHello();;    }}

To decompile the generated class file:

  

  Execution Result:

We created two anonymous objects, but the static code blocks were called only once.

Back to top 6, parent class and subclass execution order

The initialization order of the objects:

The static content of the parent class is executed first, the static content of the parent class executes, then the static content of the subclass is executed, and when the static content of the subclass is executed, the parent class constructs a block of code, and if it executes the construction blocks of the parent class, the construction code blocks of the parent classes are executed, then the parent class is executed The constructor of the parent class executes, and it goes on to see if the subclass has constructed a block of code, and if there is one, execute the subclass. The construction code block of the subclass executes and then executes the subclass's construction method.

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

Parent class: Superclass.java

+ View Code

Sub-Category: Subclass.java

+ View Code

Test:

+ View Code

Printing results:

  

Static code blocks in Java, Construction code blocks, constructors, ordinary code blocks (reprinted)

Related Article

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.