【Java基础】Java中的代码块

什么是代码块

  在Java中,用{}括起来的代码称之为代码块。

代码块分类

  1. 局部代码块:在局部变量位置且用{}括起来的代码,用于限制局部变量的生命周期。
  2. 构造代码块:在类中的成员变量位置并用{}括起来的代码,和构造方法处于同一个层级,且每次调用构造方法前会调用一次,故称之为构造代码块。
  3. 静态代码块:在类中的成员变量位置并用{}括起来的代码,但是{}前需要加一个static关键字

有何区别

  1. 局部代码块用在局部位置,用于限定生命周期。
  2. 构造代码块出现的目的是可以将多个构造方法中相同的代码放在一起,每次实例化对象前调用一次,多个对象有多次出现。
  3. 静态代码块是对类初始化时出现,多个对象共享一个。
  4. 代码块无法明确调用

示例代码

/**
 * Created by lili on 15/10/17.
 */

class CodeArea{
    //静态代码块
    static {
        int y = 100;
        System.out.println(y);
    }

    //构造代码块
    {
        int x = 10;
        System.out.println(x);
    }

    public CodeArea() {
        System.out.println("------construct function 1-------");
    }

    //构造代码块,不一定要出现在构造方法前面,可以在同一层级任何位置,但是调用的时候在构造方法之前.
    {
        int x = 20;
        System.out.println(x);
    }

    public CodeArea(int m) {
        System.out.println("------construct function 2-------");
    }

    {
        int x = 30;
        System.out.println(x);
    }

    //静态构造方法不论出现多少次,位置如果,都是在构造代码块和构造方法之前调用.
    static {
        int y = 200;
        System.out.println(y);
    }

    {
        int x = 40;
        System.out.println(x);
    }
}
public class CodeAreaTest {
    public static void main(String args[]) {
        {
            int x = 1;
            System.out.println(x);
        }
        System.out.println("--------split 1----------");

        CodeArea codeArea0 = new CodeArea();

        CodeArea codeArea1 = new CodeArea(1);


    }
}

运行结果

1
--------split 1----------
100
200
10
20
30
40
------construct function 1-------
10
20
30
40
------construct function 2-------

Process finished with exit code 0
原文地址:https://www.cnblogs.com/gslyyq/p/4887686.html