this关键字用于引用当前对象,解决变量名冲突、调用本类构造器、传递当前对象及实现链式调用。

在 Java 中,this 关键字用于明确引用当前对象的成员变量、方法或构造器,尤其在局部变量与成员变量同名时,能避免歧义。
区分同名的局部变量和成员变量
当方法参数或局部变量与类的成员变量重名时,直接使用变量名会访问局部变量。此时用 this.变量名 可明确指向成员变量。
例如:
public class Person {
private String name;
public Person(String name) {
this.name = name; // this.name 指成员变量,name 指参数
}
}
不加 this 就无法给成员变量赋值,而是给参数自身赋了值(无意义)。
在构造器中调用本类其他构造器
用 this(...) 可在一个构造器中调用同一类的其他构造器,必须作为第一条语句出现。
- 只能调用一个其他构造器
- 不能与 super(...) 同时出现在一个构造器中
- 常用于构造器重载时减少重复代码
示例:
public class Person {
private String name;
private int age;
public Person() {
this("未知", 0); // 调用含两个参数的构造器
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
将当前对象作为参数传递
在方法内部,可用 this 把当前对象本身传给其他方法或构造器,常见于监听器注册、链式调用或工厂方法中。
例如:
public class Button {
public void addActionListener(ActionListener listener) {
// ...
}
public void setup() {
addActionListener(this); // 当前 Button 实例作为监听器
}
}
前提是当前类实现了对应接口(如 ActionListener)。
返回当前对象实现链式调用
在 setter 方法中返回 this,可支持连续调用多个方法,提升 API 流畅性。
示例:
public class StringBuilderExample {
private String content = "";
public StringBuilderExample append(String str) {
this.content += str;
return this; // 返回当前对象
}
public String toString() {
return this.content;
}
}
// 使用:
new StringBuilderExample().append("Hello").append(" ").append("World");
注意:这种写法适用于无状态或状态可控的对象,不适用于不可变类设计。
不复杂但容易忽略 —— this 的本质是当前对象的引用,它让代码更清晰、更安全,尤其在命名冲突和构造逻辑组织上作用明显。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











