当前位置:网站首页>About constructive code blocks, static code blocks, and constructor execution order

About constructive code blocks, static code blocks, and constructor execution order

2022-06-13 01:28:00 superJuice

  1. Common code block : Method body of common method
  2. Building blocks of code : use {} The code of the package
  3. Static code block : use static{} The code of the package
public class MethodTest {

    private String tag;

    static {
        System.out.println(" Static code block ");
    }

    {
        System.out.println(" Building blocks of code ");
    }

    public MethodTest(String tag) {
        this.tag = tag;
        System.out.println(tag + " Constructors ");
    }

    public void test() {
        System.out.println(tag + " Common code block ");
    }

    public static void main(String[] args) {
        MethodTest test1 = new MethodTest("test1");
        test1.test();
        MethodTest test2 = new MethodTest("test2");
        test2.test();
    }

}

Running results :
Static code block
Building blocks of code
test1 Constructors
test1 Common code block
Building blocks of code
test2 Constructors
test2 Common code block

It can be seen from the running results that :

  • The construction code block calls each time an object is created , Execute before constructor .
  • Static code blocks are executed only once when the object is first created , And execute... Before constructing code blocks .
原网站

版权声明
本文为[superJuice]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280552035465.html