1 构造代码块
作用:给对象进行初始化。对象一建立就运行,并且优先于构造函数执行
构造函数是给所有对象进行统一初始化,构造函数是给对应的对象初始化
package package1; class Person{ private String name; { System.out.println("person code run"); } Person(){ System.out.println("name="+name); cry(); } Person(String name){ this.name = name; System.out.println("name="+name); cry(); } public void cry(){ System.out.println("crying"); } } public class Test1 { public static void main(String[] args){ Person p = new Person(); Person p1 = new Person("tom"); } }
结果:
person code run
name=null
crying
person code run
name=tom
时间: 2024-10-05 04:10:16