Java static 静态代码块、代码块

简述

  • static{} 静态代码块,加载类之前执行
  • {} 代码块,每次new的时候都会被执行

示例

类:


public class Student {
    int age;
    String name;
    boolean sex;
    public Student(){
        age=10;
        name="Xu";
        sex=false;
    }
    static{
        System.out.println("This is a static block");
    }
    {
        System.out.println("这是一个代码块");
    }
}

调用函数:

public class Student_test {

    public static void main(String[] args) {
        Student student1= new Student();
        Student student2= new Student();
        Student student3= new Student();
        Student student4= new Student();
        
    }
}

输出结果:

This is a static block
这是一个代码块
这是一个代码块
这是一个代码块
这是一个代码块

创建了4个对象,但是static块只执行一次,而代码块,每次创建对象,都会被执行。

猜你喜欢

转载自www.cnblogs.com/heenhui2016/p/10960809.html