在 Java 编程中,this 关键字是面向对象编程中非常重要的语法点,主要用于区分成员变量与局部变量、调用本类构造方法、返回当前对象等场景,是解决变量命名冲突、简化代码的核心工具。下面将详细讲解 this 关键字的定义、作用、格式、代码示例及使用场景,全方位掌握 this 用法。
一、this 关键字概述
1. 定义
this 是 Java 中的一个关键字,代表当前对象本身(即正在调用方法 / 构造方法的那个对象)。可以理解为:this = 当前对象的引用。
2. 核心作用
- 区分成员变量和局部变量(解决命名冲突)
- 调用本类的成员方法
- 调用本类的构造方法
- 作为返回值返回当前对象
- 作为参数传递当前对象
二、this 关键字的 4 大核心用法
1. 区分成员变量与局部变量(最常用)
当局部变量名 == 成员变量名时,Java 会优先使用局部变量。使用 this.变量名 可以明确表示:我要访问的是成员变量。
核心格式
this.成员变量名;
代码示例
public class Student {
// 成员变量
private String name;
private int age;
// 构造方法:形参(局部变量)与成员变量同名
public Student(String name, int age) {
// this.name 代表成员变量
this.name = name;
// this.age 代表成员变量
this.age = age;
}
// 打印信息
public void showInfo() {
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
}
public static void main(String[] args) {
Student stu = new Student("小明", 18);
stu.showInfo();
}
}
输出结果
姓名:小明
年龄:18
2. 调用本类的成员方法
在一个成员方法中,可以使用 this.方法名() 调用本类的其他成员方法。
代码示例
public class Test {
public void method1() {
System.out.println("方法1执行");
}
public void method2() {
// 调用本类 method1
this.method1();
System.out.println("方法2执行");
}
public static void main(String[] args) {
Test t = new Test();
t.method2();
}
}
输出结果
方法1执行
方法2执行
3. 调用本类的构造方法
使用 this(参数) 可以在构造方法中调用本类的其他构造方法。
注意事项
- 必须放在构造方法第一行
- 只能调用一次
代码示例
public class User {
private String name;
private int age;
// 无参构造
public User() {
// 调用本类有参构造
this("未知", 0);
System.out.println("无参构造执行");
}
// 有参构造
public User(String name, int age) {
this.name = name;
this.age = age;
System.out.println("有参构造执行");
}
public void show() {
System.out.println(name + "," + age);
}
public static void main(String[] args) {
User user = new User();
user.show();
}
}
输出结果
有参构造执行
无参构造执行
未知,0
4. 作为返回值,返回当前对象
return this; 可以返回当前对象,支持链式调用。
代码示例
public class Person {
private String name;
public Person setName(String name) {
this.name = name;
// 返回当前对象
return this;
}
public void show() {
System.out.println("名字:" + name);
}
public static void main(String[] args) {
// 链式调用
new Person().setName("小红").show();
}
}
输出结果
名字:小红
三、this 关键字核心特点
- 代表当前对象,谁调用方法,this 就代表谁
- 只能在成员方法、构造方法中使用
- 静态方法(static)中不能使用 this
- 主要解决变量命名冲突问题
- 可以调用成员、方法、构造器





