Java中的this关键字的用法

解释 Java 中 this 关键字的常见用法:

public class ThisKeywordExamples {
   
    // 实例变量
    private String name;
    private int age;
    private double salary;

    // 1. 区分实例变量和局部变量(构造方法中)
    public ThisKeywordExamples(String name, int age) {
   
        // this.name 表示实例变量,name 表示构造方法的参数(局部变量)
        this.name = name;
        this.age = age;
    }

    // 2. 区分实例变量和局部变量(普通方法中)
    public void setSalary(double salary) {
   
        // this.salary 表示实例变量,salary 表示方法参数
        this.salary = salary;
    }

    // 3. 调用当前类的其他构造方法(必须位于构造方法的第一行)
    public ThisKeywordExamples(String name, int age, double salary) {
   
        // 调用上面的双参数构造方法
        this(name, age);
        this.salary = salary;
    }

    // 4. 调用当前类的其他方法
    public void printFullInfo() {
   
        System.out.println("完整信息:");
        // 调用当前类的 printBasicInfo() 方法
        this.printBasicInfo();
        System.out.println("薪资:" + this.salary);
    }

    public void printBasicInfo() {
   
        System.out.println("姓名:" + this.name + ",年龄:" + this.age);
    }

    // 5. 作为方法的返回值(返回当前对象)
    public ThisKeywordExamples updateAge(int newAge) {
   
        this.age = newAge;
        // 返回当前对象的引用,可实现方法链式调用
        return this;
    }

    // 6. 作为参数传递给其他方法
    public void sendToDatabase() {
   
        // 将当前对象作为参数传递给其他方法
        DatabaseUtil.save(this);
    }

    public static void main(String[] args) {
   
        // 测试构造方法中的 this 用法
        ThisKeywordExamples person = new ThisKeywordExamples("张三", 25);
        person.setSalary(8000.0);

        // 测试调用当前类方法的 this 用法
        person.printFullInfo();

        // 测试作为返回值的 this 用法(链式调用)
        person.updateAge(26).printBasicInfo();

        // 测试作为参数的 this 用法
        person.sendToDatabase();
    }
}

// 辅助类:演示 this 作为参数传递
class DatabaseUtil {
   
    // 接收一个对象参数并保存
    public static void save(ThisKeywordExamples obj) {
   
        System.out.println("保存对象到数据库:" + obj);
    }
}
 
 

this 关键字的主要用法说明:

  1. 区分实例变量和局部变量
    当方法参数或局部变量与类的实例变量同名时,使用 this.变量名 表示实例变量,避免命名冲突。
    例如在构造方法和 setSalary 方法中,this.name 明确指向类的实例变量。

  2. 调用当前类的其他构造方法
    通过 this(参数列表) 可以在一个构造方法中调用另一个构造方法,减少代码重复。
    注意:这种调用必须放在构造方法的第一行。

  3. 调用当前类的其他方法
    使用 this.方法名() 可以调用当前类的其他方法,增强代码可读性(即使省略 this 也能正常工作,但显式写出更清晰)。

  4. 作为方法返回值
    在方法中返回 this 可以返回当前对象的引用,从而实现方法的链式调用(如示例中的 updateAge(26).printBasicInfo())。

  5. 作为参数传递
    this 可以代表当前对象,作为参数传递给其他方法(如示例中传递给 DatabaseUtil.save() 方法)。

posted @ 2025-10-19 12:04  yijg9998  阅读(9)  评论(0)    收藏  举报