Home > Java > javaTutorial > body text

Java Improvement Chapter (11)-----Code Block

黄舟
Release: 2017-02-10 11:20:12
Original
1128 people have browsed it

During the programming process we may encounter programs of the following form:

public class Test {
    {
        ////
    }
}
Copy after login


             We call this form of program segment a code block. The so-called code block uses curly brackets ({}) to encapsulate multiple lines of code together to form an independent A data body used to implement a specific algorithm. Generally speaking, a code block cannot be run alone, it must have a running body. There are four main types of code blocks in Java:

## 1. Ordinary code blocks

##       Ordinary code blocks are The one we use most and is the most common is the code segment enclosed in {} after the method name. An ordinary code block cannot exist alone, it must follow the method name. It must also be called using the method name.

public class Test {
    public void test(){
        System.out.println("普通代码块");
    }
}
Copy after login


## 2. Static code block

      

When we think of static, we will think of static. A static code block is a code segment enclosed in {} that is modified with static. Its main purpose is to initialize static properties.

public class Test {
    static{
        System.out.println("静态代码块");
    }
}
Copy after login

## 3. Synchronous code block

      

Use the synchronized keyword to modify the code snippet and use "{}" to enclose it. It means that only one thread can enter the method block at the same time, which is a multi-thread protection mechanism.

Four, the constructed code block

# directly defines the code without any modifiers, prefixes, suffixes in the class Blocks are blocks of constructed code. We understand that a class must have at least one constructor, which is called when an object is created. The construction code block, like the constructor, is also called when an object is generated. So when is the construction code called? How to call it? Look at the following code:

##

public class Test {
    /**
     * 构造代码
     */
    {
        System.out.println("执行构造代码块...");
    }
    
    /**
     * 无参构造函数
     */
    public Test(){
        System.out.println("执行无参构造函数...");
    }
    
    /**
     * 有参构造函数
     * @param id  id
     */
    public Test(String id){
        System.out.println("执行有参构造函数...");
    }
}
Copy after login

##The above defines a very simple Class, this class contains parameterless constructors, parameterized constructors and construction code blocks. At the same time, as mentioned above, code blocks do not have the ability to run independently. They must have a carrier that can carry them. So what will happen to the compiler? What about constructing code blocks? The compiler will insert the code blocks in their order (if there are multiple code blocks) at the front of all constructors, thus ensuring that no matter which constructor is called, all constructed code blocks will be executed. The above code is equivalent to the following form:

##

public class Test {
    /**
     * 无参构造函数
     */
    public Test(){
        System.out.println("执行构造代码块...");
        System.out.println("执行无参构造函数...");
    }
    
    /**
     * 有参构造函数
     * @param id  id
     */
    public Test(String id){
        System.out.println("执行构造代码块...");
        System.out.println("执行有参构造函数...");
    }

}

       运行结果

public static void main(String[] args) {
        new Test();
        System.out.println("----------------");
        new Test("1");
    }
------------
Output:
执行构造代码块...
执行无参构造函数...
----------------
执行构造代码块...
执行有参构造函数...
Copy after login

## It can be seen from the running results that when new an object, the construction code is always executed first, and then the constructor function is executed. However, one thing to note is that the construction code is not run before the constructor, it is executed based on the constructor. It is precisely because the construction code block has these characteristics that it is often used in the following scenarios:


        

If there are several constructors in a class, these constructors need to initialize instance variables. If we instantiate directly in the constructor, it will definitely occur A lot of repeated code, cumbersome and poorly readable. Here we can make full use of constructed code blocks to achieve this. This takes advantage of the fact that the compiler adds a block of construction code to each constructor.

         

2. Initialize the instance environment

一个对象必须在适当的场景下才能存在,如果没有适当的场景,则就需要在创建对象时创建此场景。我们可以利用构造代码块来创建此场景,尤其是该场景的创建过程较为复杂。构造代码会在构造函数之前执行。

上面两个常用场景都充分利用构造代码块的特性,能够很好的解决在实例化对象时构造函数比较难解决的问题,利用构造代码不仅可以减少代码量,同时也是程序的可读性增强了。特别是当一个对象的创建过程比较复杂,需要实现一些复杂逻辑,这个时候如果在构造函数中实现逻辑,这是不推荐的,因为我们提倡构造函数要尽可能的简单易懂,所以我们可以使用构造代码封装这些逻辑实现部分。

五、 静态代码块、构造代码块、构造函数执行顺序

从词面上我们就可以看出他们的区别。静态代码块,静态,其作用级别为类,构造代码块、构造函数,构造,其作用级别为对象。

1、 静态代码块,它是随着类的加载而被执行,只要类被加载了就会执行,而且只会加载一次,主要用于给类进行初始化。

2、 构造代码块,每创建一个对象时就会执行一次,且优先于构造函数,主要用于初始化不同对象共性的初始化内容和初始化实例环境。

3、 构造函数,每创建一个对象时就会执行一次。同时构造函数是给特定对象进行初始化,而构造代码是给所有对象进行初始化,作用区域不同。

通过上面的分析,他们三者的执行顺序应该为:静态代码块 > 构造代码块 > 构造函数。


public class Test {
    /**
     * 静态代码块
     */
    static{
        System.out.println("执行静态代码块...");
    }
    
    /**
     * 构造代码块
     */
    {
        System.out.println("执行构造代码块...");
    }
    
    /**
     * 无参构造函数
     */
    public Test(){
        System.out.println("执行无参构造函数...");
    }
    
    /**
     * 有参构造函数
     * @param id
     */
    public Test(String id){
        System.out.println("执行有参构造函数...");
    }
    
    public static void main(String[] args) {
        System.out.println("----------------------");
        new Test();
        System.out.println("----------------------");
        new Test("1");
    }
}
-----------
Output:
执行静态代码块...
----------------------
执行构造代码块...
执行无参构造函数...
----------------------
执行构造代码块...
执行有参构造函数...
Copy after login


以上就是java提高篇(十一)-----代码块的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!