在java中,关键字this代表当前对象的引用。
一、区分实例变量和局部变量
当方法存在于实例变量同名的局部变量时,使用this关键字指示使用的是实例变量。
public class Person {
private String name;
public void setName(String name) {
this.name = name; // 使用this来指代实例变量name
}
}
二、调用其他构造函数
在一个构造函数中,可以使用this()来调用同一个类中的其他构造函数。
三、返回当前对象
在方法中使用return this;可以返回当前对象的引用。
public class practice07 {
private String name;
private int age;
public practice07(){//无参构造方法
this("Bob",18);
display();
}
public practice07(String name,int age){//带参构造方法
this.name=name;
this.age=age;
}
public practice07 set(String name,int age){//设置姓名和年龄的方法
this.name=name;
this.age=age;
return this;
}
public void display(){//显示对象属性的方法
System.out.println("Name:"+name+"\nAge:"+age);
}
public static void main(String[] args) {
practice07 per=new practice07().set("Alice",18);
per.display();
}
}