/** 静态代码块:随着类的加载而执行,只执行一次,优先与main函数的执行 */ class Demo12 { static { System.out.println("a"); } public static void main(String[] args) { //new Test(); //Test.show(); Test t = null; } static { System.out.println("b"); } } class Test { static int num = 10; static { System.out.println(num); } public static void show() { System.out.println("show"); } } //执行结果为a,b,c,show 构造代码块 /** 构造代码块:对象一创建就执行 ,优先于构造函数的执行; 实现所有对象的初始化 */ class Demo13 { public static void main(String[] args) { People person1 = new People(23,"lisi"); People person2 = new People(20,"wangwu"); System.out.println(person1.age + " " + person1.name);//3 System.out.println(person2.age + " " + person2.name);//4c } } class People { int age; String name; { System.out.println("构造代码块");//1 可以实现所有对象的一个初始化,当所有对象都有这个共性时使用 } People(int age,String name) { this.age = age; this.name = name; System.out.println("构造函数执行"); //2 } }