在java中,this除了代表类的对象外,还可以在无参构造函数中,用this()方法调用有参构造函数。
应用:如果一个类的实例化中,在调用无参构造函数时,如果有属性是有默认值的情况下,可以使用。但需要的注意的是this()函数需要写在无参构造函数的第一行。
例子:
public class Student{
privite int age;
privite String className;
public Student(int age, String className){
this.age = age;
this.className = className;
}
//无参构造函数
public Student(){
this(18,"终极一班");
}
public static void main(String[] args){
Student student = new Student();
//此时student默认属性age=18,className="终极一班"
}
}