一、三大核心用法

1. 区分 成员变量 和 局部变量(最常用)

局部变量/形参 和 成员变量重名时,用 this.成员变量 指明访问类的成员变量

public class Person {
    String name; // 成员变量

    // 形参 name 和 成员变量重名
    public void setName(String name) {
        this.name = name; 
        // this.name → 成员变量
        // 右边 name → 方法形参
    }
}

2. 调用本类其他构造方法

语法:this(参数列表);

  • 必须写在构造器第一行
  • 构造方法之间互相调用,不能循环调用
public class Student {
    String name;
    int age;

    // 无参构造
    public Student() {
        this("张三", 18); // 调用本类有参构造
        System.out.println("无参构造执行");
    }

    // 有参构造
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

3. 代表当前对象本身

  • this 可作为返回值实参传递,指代当前调用方法的对象。
public class Demo {
    public Demo getSelf() {
        return this; // 返回当前对象
    }

    public static void main(String[] args) {
        Demo d = new Demo();
        Demo d2 = d.getSelf();
        System.out.println(d == d2); // true
    }
}

二、使用规则 & 注意事项

  1. 不能在静态方法/静态代码块中使用 this
    静态属于类,不属于某个实例对象。
  2. this(...) 调用构造器必须放在第一行,一个构造器只能调用一次。
  3. 方法中变量不重名时,this. 可省略。
  4. this 只能指向当前实例对象,不能指代静态资源。

三、和 super 简单区分(易混点)

  • this:当前本类对象
  • super:当前对象的父类对象
  • 两者调用构造器时,都要求写在第一行,不能同时使用

四、完整综合示例

public class Cat {
    private String color;

    // 构造器1
    public Cat() {
        this("黑色"); // 调用本类有参构造
    }

    // 构造器2
    public Cat(String color) {
        this.color = color; // 区分成员变量与形参
    }

    public void show() {
        System.out.println("猫咪颜色:" + this.color);
    }

    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.show(); // 猫咪颜色:黑色
    }
}

更多推荐