Java 中 this 的作用

this 的作用就是用来区分类的成员变量和局部变量。

我们来看下面这个例子:

class Tmp {
    int x, y;
    Tmp(int x) {
        x = 4;
        y = 5;
    }
}

public class Main {
    static public void main(String[] args) {
        Tmp a = new Tmp(15);
        System.out.printf("%d %d
", a.x, a.y);
    }
}

输出了:0 5

由于方法中局部变量屏蔽了成员变量,导致我们没让实例 a 的成员变量 x 成为 4。这个时候要想在方法中修改被屏蔽的成员变量,就要用到 this

class Tmp {
    int x, y;
    Tmp(int x) {
        this.x = 4;
        y = 5;
    }
}

public class Main {
    static public void main(String[] args) {
        Tmp a = new Tmp(15);
        System.out.printf("%d %d
", a.x, a.y);
    }
}

像这样,我们就成功的将实例 a 的成员变量修改成了 4 5。

原文地址:https://www.cnblogs.com/Node-Sans-Blog/p/13666414.html