Java static static block of code, code blocks

Brief

  • Before performing static {} static block of code, the class loading
  • {} Block, each time when new will be performed

Examples

class:


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("这是一个代码块");
    }
}

call function:

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();
        
    }
}

Output:

This is a static block
which is a block of code
which is a code block
which is a block of code
which is a code block

Created four objects, but static block is executed only once, and code blocks, each time you create an object, will be executed.

Guess you like

Origin www.cnblogs.com/heenhui2016/p/10960809.html