Java this关键字详解

    |     2015年3月30日   |   Java面向对象   |     0 条评论   |    1637

this 用来表示当前对象:哪个实例正在执行这段代码,this 就指向谁。通过它可以访问本对象的成员变量和实例方法。

this 只在实例化之后才有意义,静态方法里没有当前对象,因此不能用 this。

常见用法可以先放在一张表里对照:

写法 含义 注意
this.成员 访问当前对象的字段或方法 没有重名时可以省略
this.x = x 形参与成员同名时,区分开 左边是成员,右边是局部变量
this(…) 在构造方法里调用本类另一个构造方法 必须写在第一句;不能和 super() 同时出现
方法(this) 把当前对象引用传给别的方法 常用于回调、互相持有引用

一、指向当前实例

下面 obj 是 Demo 的一个实例。执行 obj.sum() 时,方法里的 this 就和 obj 指向同一个对象:this.x + this.y 等价于 obj.x + obj.y。

public class Demo {
    public int x = 10;
    public int y = 15;
    public void sum() {
        int z = this.x + this.y;
        System.out.println("x + y = " + z);
    }
    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.sum();
    }
}

运行结果:x + y = 25。没有重名时,写成 x + y 也行,编译器会默认把成员和 this 绑在一起。

二、区分同名变量

形参作用域是整个方法体,属于局部变量。构造方法里形参和成员同名时,直接写 name 访问到的是形参;要给成员赋值,必须写 this.name。

public class Demo {
    public String name;
    public int age;
    public Demo(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void say() {
        System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
    }
    public static void main(String[] args) {
        Demo obj = new Demo("新华苑", 3);
        obj.say();
    }
}

运行结果:网站的名字是新华苑,已经成立了3年。say() 里没有同名局部变量,写 name 或 this.name 效果相同。

三、在构造方法里调用另一个构造方法

this(参数) 不是普通方法调用,而是构造方法链式调用:让无参构造把工作转交给有参构造。它必须作为构造方法的第一句。

public class Demo {
    public String name;
    public int age;
    public Demo() {
        this("新华苑", 3);
    }
    public Demo(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void say() {
        System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
    }
    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.say();
    }
}

运行结果同样是:网站的名字是新华苑,已经成立了3年。三条硬规则:

  • 调用必须放在构造方法最起始的位置。
  • 不能在构造方法以外调用构造方法(不能写 this() 当普通方法用)。
  • 一个构造方法里只能调用一个构造方法;this() 和 super() 不能同时出现。

上面用到了方法重载:同名方法只要参数列表不同就可以共存,后续章节会展开。

四、作为参数传递

需要把当前对象交给另一个完全独立的类时,把 this 当作参数即可。

public class Demo {
    public static void main(String[] args) {
        new A();
    }
}
class A {
    public A() {
        new B(this).print();  // 匿名对象
    }
    public void print() {
        System.out.println("Hello from A!");
    }
}
class B {
    A a;
    public B(A a) {
        this.a = a;
    }
    public void print() {
        a.print();
        System.out.println("Hello from B!");
    }
}

运行结果:

Hello from A!
Hello from B!

匿名对象就是没有名字的对象。只用一次时,new B(this).print() 等价于先 new B(this) 再立刻调用 print()。

一句话总结:this 就是当前实例;重名时用 this. 成员,构造里用 this() 转调另一个构造,需要把自己交给别人时把 this 当参数传出去。

转载请注明来源:Java this关键字详解
本文链接地址:https://ai.zhousir.top/?p=91
回复 取消