静态代码块、非静态代码块(构造块)的区别

1、静态代码块是在类加载的时候执行的,格式为static{...}

2、非静态代码块(构造块),每调用一次构造方法就会执行一次,可以提取构造函数中公共的部分放在构造块,格式为{...}

代码示例:

public class Student {
    private String banji;
    private String name;
    private String age;
    static {
        System.out.println("加载1班的同学");
    }
    {
        this.banji="1班";
    }
    public void init(){
        System.out.println("init execute");
    }

    public Student(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getBanji() {
        return banji;
    }

    public void setBanji(String banji) {
        this.banji = banji;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}


public class Test {
    public static void main(String[] args){
        Student student=new Student("bonnie","10");
        Student student2=new Student("xiaohong","20");

        System.out.println(student.getBanji()+","+student.getName()+","+student.getAge());
        System.out.println(student2.getBanji()+","+student2.getName()+","+student2.getAge());
    }
}

代码输出:

加载1班的同学
1班,bonnie,10
1班,xiaohong,20

 

posted @ 2020-02-29 19:05  第二人生Bonnie  阅读(341)  评论(0编辑  收藏  举报