Java static 静态代码块代码块

Posted heenhui2016

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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块只执行一次,而代码块,每次创建对象,都会被执行。

以上是关于Java static 静态代码块代码块的主要内容,如果未能解决你的问题,请参考以下文章