Java / 系统课时

this关键字的使用

this关键字的使用

this 表示当前对象引用,主要用于区分同名字段与参数、调用同类构造方法,以及返回当前对象。本课通过一个可链式配置的个人资料对象,集中验证这三种常见用法。

学习目标

  • 理解 this 所指向的当前对象
  • 使用 this.field 解决名称遮蔽
  • 正确使用 this(...) 和返回 this

this 的三种常见用法

在实例方法和构造方法中,this 指向正在操作或初始化的对象。参数与字段同名时,裸写名称表示局部参数,this.name 才表示当前对象字段。

this(...) 用于调用同一类中的其他构造方法,在本课采用的 Java 17 中,显式调用必须位于构造方法的第一条语句。实例方法也可以返回 this,让调用方连续调用多个配置方法,但每一步仍要保证对象状态合法。

主示例

下面同时演示字段赋值、构造委托和链式调用。代码保存为 Main.java。

java
public class Main {
    public static void main(String[] args) {
        Profile profile = new Profile("小周")
                .setCity("深圳")
                .setAge(28);

        profile.print();
    }
}

class Profile {
    private final String name;
    private String city;
    private int age;

    Profile(String name) {
        // 简化构造方法委托给完整构造方法
        this(name, "未设置", 0);
    }

    Profile(String name, String city, int age) {
        // this.field 明确表示当前对象的字段
        this.name = name;
        this.city = city;
        setAge(age);
    }

    Profile setCity(String city) {
        // 返回当前对象,使后续配置可以继续链式调用
        this.city = city;
        return this;
    }

    Profile setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("年龄不能为负数");
        }
        this.age = age;
        return this;
    }

    void print() {
        System.out.println(name + ",城市=" + city + ",年龄=" + age);
    }
}

编译并运行:

bash
javac Main.java
java Main

预期输出:

text
小周,城市=深圳,年龄=28

关键边界

写成 name = name 只会把参数赋给自身,字段仍保持原值。静态方法没有当前实例,因此不能直接使用 this。

在 Java 17 中,显式 this(...) 和 super(...) 都必须位于构造方法第一条语句,而且同一个构造方法中不能同时直接调用二者。链式方法会修改当前对象时,应通过命名或文档明确这一点。

确认链式调用返回的是当前对象

在 main 末尾运行这个对照。setCity 的返回值仍指向传入的 original 对象,后续通过任一引用改变它,都会反映到同一份资料。完整构造方法与 setAge 复用年龄校验,直接调用构造方法也无法建立负年龄对象。

java
Profile original = new Profile("小周");
Profile returned = original.setCity("杭州");
System.out.println(original == returned);
returned.setAge(30);
original.print();
try {
    new Profile("小周", "杭州", -1);
} catch (IllegalArgumentException e) {
    System.out.println(e.getMessage());
}

预期输出

text
true
小周,城市=杭州,年龄=30
年龄不能为负数

如果漏写 this.city 并写成 city = city,第一行仍然是 true,但打印的城市会保留默认值。这个对照可区分两件事:返回了哪个对象,以及字段是否真的发生了修改。Java 17 构造方法调用规则

按自己的节奏,确认真正理解。

目录与阅读设置

记录一个想法

this关键字的使用

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通