对象初始化过程一共有四步
用new创建并初始化对象步骤:
给对象的实例变量(非“常量”)分配内存空间,默认初始化成员变量;
成员变量声明时的初始化;
初始化块初始化(又称为构造代码块或非静态代码块);
构造方法初始化
public class Student{
String stuName="";//姓名
int stuAge="-1";//年龄
//对象的初始化块初始化
{System.out.println("使用初始块初始化");
this.stuName="雷静";
this.stuAge=22;
}//无参构造方法
public Student(){
System.out.println("使用无参构造函数初始化");
}//构造方法,用户初始化对象的成员变量
public Student(String name,int age){
System.out.println("使用有参构造函数初始化");
this.stuName=name;
this.stuAge=age;
}
}
public class Teststudent(){
public static void main(String[] args) {
//构造方法初始化成员变量在对象初始块化初始化之后
Student temp=new student("王云",22);
System.out.println(temp.stuName,temp.stuAge);
}
}