演示----块
块的结构: 用一堆大括号括起来就是块 用static修饰的块,称为静态块; 没有用static修饰的块,称为实例块; 程序演示: public class Student { private String name; private int age; static int count;//人数 静态块:在类加载的时候执行 static { System.out.println("执行了静态块"); count++; } 实例块:在每次调用构造方法之前,都被执行一次 { System.out.println("执行了实例块"); count++; } public Student() { System.out.println("执行了 Student()构造方法"); count++; } public Student(String name) { System.out.println("执行了 Student(String name)构造方法"); this.name = name; count++; } public Student(String name, int age) { System.out.println("执行了Student(String name, int age) 构造方法"); this.name = name; this.age = age; count++; } }
测试: public static void main(String[] args) { Student s1=new Student(); Student s2=new Student("学生1"); Student s3=new Student("学生2",12); System.out.println("学生人数:"+Student.count); } |
结果:
|