代码块分类及执行顺序

根据代码块定义的位置以及关键字,可以分为以下四种:

  • 普通代码块
  • 构造代码块
  • 静态块
  • 同步代码块

一、普通代码块
定义在方法中的代码块,如:

//直接使用{}定义
public class Main {
    public static void main(String[] args) {
        {
            int x = 1;
            System.out.println("x = " + x);
        }
        {
            int y = 2;
            System.out.println("y = " + y);
        }
    }
}

二、构造代码块
定义在类中的代码块(不加修饰符),也称实例代码块,一般用于初始化实例成员变量。如:

class Student{
    private String name;
    private int age;
    //构造函数
    public Student(){
        System.out.println("we are winner");
    }
    //构造代码块
    {
        this.age = 20;
        this.name = "jack";
        System.out.println("I am the best");
    }

    public void show(){
        System.out.println("name:" + name + " age:" + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.show();
    }
}

输出:
I am the best
we are winner
name:jack age:20

注意:实例代码块优先于构造函数执行。
三、静态代码块
使用static定义的代码块,一般用于初始化静态成员属性。如:

class Student{
    private String name;
    private int age;
    private static int count = 0;//静态成员变量,存于共享区

    //构造函数
    public Student(){
        System.out.println("we are winner");
    }

    //构造代码块(实例代码块)
    {
        this.age = 20;
        this.name = "Run";
        System.out.println("I am the best");
    }

    //静态代码块
    static {
        count = 10;
        System.out.println("I am static and count = " + count);
    }

    public void show(){
        System.out.println("name:" + name + " age:" + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student();
        Student student2 = new Student();
        student1.show();
        student2.show();
    }
}

输出:
I am static and count = 10
I am the best
we are winner
I am the best
we are winner
name:Run age:20
name:Run age:20
注意事项:

  • 不管生成多少个对象,静态代码块只会执行一次,且是最先执行。
  • 静态代码块执行完毕后,实例代码块(构造块)执行,再构造函数执行。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值