[笔记]有关Static初始化的一点小小记忆

来源:互联网 发布:非mac安装os x 编辑:程序博客网 时间:2024/05/13 17:25

Q1:看下列代码,分析输出结果?

public class Test {    static {        System.out.println("static");//-----1    }    public Test() {        System.out.println("Test");//-----2    }    public static void main(String[] args) {        Test test = new Test();    }}

A:

staticTest

Thinking:静态代码块先于构造器执行。

Q2:看下列代码,分析输出结果?

public class Test {    static Test test1 = new Test();//-----1    static {        System.out.println("static");//-----2    }    public Test() {//-----3        System.out.println("Test");    }    public static void main(String[] args) {        Test test1 = new Test();    }}

A:

TeststaticTest

Q:看下列代码,分析输出结果?

public class Test {    static {        System.out.println("static");//-----1    }    public Test() {//-----3        System.out.println("Test");    }    public static void main(String[] args) {        Test test1 = new Test();    }    static Test test1 = new Test();//-----2}

A:

staticTestTest

Thinking:静态代码块按顺序执行。

Q3:看下列代码,分析输出结果?

public class Test {    static {        System.out.println("static");//-----1    }    public Test() {//------3,4        System.out.println("Test");    }    public static void main(String[] args) {        Test test1 = new Test();        Test test2 = new Test();    }    static Test test1 = new Test();//-----2}

A:

staticTestTestTest

Thinking:静态代码块只在类加载的时候初始化一次,之后都不再执行。

总结:static修饰的变量在构造器之前(除非该类也是static修饰,类似Q1)按顺序初始化,而且只加载一次。


tip:笔者经验非常有限,如有错误或者描述不当的地方,请轻喷。。。。。。

0 0
原创粉丝点击