• 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块只执行一次,而代码块,每次创建对象,都会被执行。

相关文章:

  • 2022-12-23
  • 2021-06-08
  • 2021-07-25
  • 2022-12-23
  • 2021-10-02
  • 2022-02-09
  • 2021-05-25
  • 2021-12-09
猜你喜欢
  • 2022-02-28
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案