常见用法
-
引用当前对象的成员变量或方法:在一个类的方法中,如果参数名称与类的成员变量名称相同,可以使用“this”关键字来引用成员变量,以区分局部变量和成员变量。
-
在构造函数中调用其他构造函数:在一个类的构造函数中,可以使用“this”关键字来调用同一类的另一个构造函数。
-
返回当前对象的引用:在一个方法中,可以使用“return this;”语句来返回当前对象的引用。
-
将当前对象作为参数传递给其他方法:在一个类的方法中,可以使用“this”关键字将当前对象作为参数传递给其他方法。
demo示例
示例1:使用this关键字引用成员变量
构造函数中的参数与类的成员变量名称相同,因此可以使用this关键字引用成员变量。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void printPerson() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
// 使用示例
Person person = new Person("Alice", 25);
person.printPerson();
示例2:使用this关键字调用其他构造函数
第二个构造函数使用this关键字调用了第一个构造函数
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(int size) {
this(size, size);
}
}
// 使用示例
Rectangle rect1 = new Rectangle(10, 20);
Rectangle rect2 = new Rectangle(5);
示例3:使用this关键字作为方法参数
introduce()方法接受一个Person对象作为参数,使用this关键字引用当前对象,然后将当前对象和另一个Person对象一起传递给该方法
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void introduce(Person friend) {
System.out.println("Hi, my name is " + this.name);
System.out.println("My friend's name is " + friend.name);
}
}
// 使用示例
Person alice = new Person("Alice");
Person bob = new Person("Bob");
alice.introduce(bob);