Java 初始化块

一个class里面可以出现
成员变量
方法
构造器
初始化块

语法有

static {
}

{
}

总结如下:

  • 执行顺序为 static初始化块 -> 初始化块 -> 构造器
  • 成员变量的初始化与初始化块按代码先后决定,在构造器之前
  • static初始化块只会执行1次

eg1:

class Test
{
    {
        System.out.println("hello");
    }
}

public class Main
{
    public static void main(String[] args) {
    }
}

无输出
eg2:

class Test
{
    {
        System.out.println("hello");
    }
}

public class Main
{
    public static void main(String[] args) {
        Test test = new Test();
    }
}

可见 new Test() 调用了才会执行初始化块

eg3

class Test
{
    Test() {
        System.out.println("world");
    }
    {
        System.out.println("hello");
    }

}

public class Main
{
    public static void main(String[] args) {
        Test test = new Test();
    }
}

输出Hello world
可见初始化块在构造函数之前执行。

eg4

class Test
{
    int x = 1;
    {
        x = 2;
    }
}

public class Main
{
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.x);
    }
}

输出2

class Test
{
    {
        x = 2;
    }
    int x = 1;
}

public class Main
{
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.x);
    }
}

输出1
可以见与成员变量初始化的顺序与代码顺序有关。
eg5

class Test
{
    Test () {
        x = 3;
    }
    {
        x = 2;
    }
    int x = 1;

}

public class Main
{
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.x);
    }
}

输出3
可见构造器永远最后执行

eg6

class Test
{
    static int x = 2;
    static {
        x = 1;
        System.out.println("hello");
    }
    {
        System.out.println("world");
    }
}

public class Main
{
    public static void main(String[] args) {
        System.out.println(Test.x);
    }
}
输出
hello
2

没有输出world,可见直接访问静态成员不会调用非静态的初始化块。
eg7

class Test
{
    static {
        x = 1;
        System.out.println("hello");
    }
    {
        System.out.println("world");
    }
    static int x = 2;
}

public class Main
{
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        System.out.println(Test.x);
    }
}

输出
hello
world
world
2
可见static 初始化块只会执行一次,并且在普通初始块之前执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值