1 package java_test; 2 public class A6_32 { 3 public static void main(String[] args){ 4 Person A=new Person(); 5 Person B=new Person("小七"); 6 } 7 } 8 /*构造代码块特点:对象一建立就运行,而且优先于构造函数执行 9 * 作用:对对象进行初始化 10 * 和构造函数的区别:构造方法是给对应的对象进行初始化 11 * 构造代码块是给所有的对象进行统一的初始化 12 * 构造代码块中定义的是不同对象共性的初始化内容 13 */ 14 class Person{ 15 String name; 16 int age; 17 public Person(){ 18 System.out.println("我是无参构造方法"); 19 } 20 public Person(String name){ 21 this.name=name; 22 System.out.println("我是有1个参数构造方法"); 23 } 24 { 25 System.out.println("我是构造代码块");//这里是构造代码块 26 } 27 28 29 }
执行结果:
我是构造代码块
我是无参构造方法
我是构造代码块
我是有1个参数构造方法