静态块和构造块的区别

看下面代码

public class StaticTest {

    {
        System.out.println("构造块");
    }

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

    public StaticTest(int index) {
        System.out.println("index" + index);
    }


    public static void main(String[] args) {
        new StaticTest(1);
        new StaticTest(2);
    }
}

输出结果为:

在这里插入图片描述

从程序来看静态块static{…}在一个程序里面只会执行一次,而构造块{…}只要建立一个对象,构造代码块都会执行一次.静态代码块优先于构造块和主方法。

猜你喜欢

转载自blog.csdn.net/qq_42651904/article/details/87865828
今日推荐