Second, Java object-oriented (10) _ code block

2018-05-02

 

code block

 

What is a code block?

  In a class or method, use "{}" to encapsulate multiple lines of code together to form an independent code area, which constitutes a code block.

  The variables in the code block are local variables and are only valid within the {} before and after the area where they are located.

 

Classification of code blocks

  According to the position of the code block definition, it is divided into three types

1. Local code block: The data enclosed in a pair of "{}" in the method is the local code block.

  Generally, we will not use local code blocks directly, but we will combine keywords such as if, while, for, try, etc., to represent a code area.

 

2. Initialization code block (construction code block): It is the code defined directly in the class and enclosed in "{}".

  The constructor is used every time an object is created, and the initialization block is executed before the constructor is called.

  It can be seen by decompilation that the initialization code block is also used as the initial statement of the constructor.

  We generally do not use initialization code blocks. Even if we do initialization operations, we usually do them in the constructor. If there are more codes for initialization operations, then the structure of the constructor is confusing at this time.

  At this point, you can define a method specifically for initialization (object initialization), and then call it in the constructor.

 

3. Use static-modified initialization code block: (In the member position in the class, the code enclosed in "{}" is only modified with static.)

  Execute the static block of code before the main method, and only once

 

The main method is the entry point of the program, why does the static code block execute before the main method?

  Because static members are loaded as bytecode is loaded, they are also loaded into the JVM. At this point the main method has not been executed, because the method requires a JVM call.

  That is, the bytecode is loaded into the JVM first, and then the JVM calls the main method.

  Generally, we use it for initialization operations (class initialization), loading resources, loading configuration files, and so on.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325216983&siteId=291194637