使用"this"和方法(在Java中)

use*_*155 15 java methods this

用Java中的方法使用"this"怎么样?它是可选的还是有需要使用它的情况?

我遇到的唯一情况是在类中调用方法中的方法.但它是可选的.这是一个愚蠢的例子,只是为了表明我的意思:

public class Test {

    String s;

    private String hey() {
        return s;
    }

    public String getS(){
        String sm = this.hey();
        // here I could just write hey(); without this
        return sm;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 36

您需要它的三个明显情况:

  • 在与构造函数的第一部分相同的类中调用另一个构造函数
  • 区分局部变量和实例变量(无论是在构造函数中还是在任何其他方法中)
  • 将对当前对象的引用传递给另一个方法

以下是这三个例子:

public class Test
{
    int x;

    public Test(int x)
    {
        this.x = x;
    }

    public Test()
    {
        this(10);
    }

    public void foo()
    {
        Helper.doSomethingWith(this);
    }

    public void setX(int x)
    {
        this.x = x;
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信也有一些奇怪的情况使用你需要的内部类,super.this.x但它们应该避免,因为非常模糊,IMO :)

编辑:我想不出任何为什么你想要它直接this.foo()方法调用的例子.

编辑:saua在晦涩的内部类例子上做出了贡献:

我认为晦涩的情况是:OuterClass.this.foo()foo()从具有foo()方法的Inner类中的代码访问外部类时.


Yes*_*ke. 5

我使用“this”来阐明代码,通常是暗示我正在调用实例方法而不是访问类级方法或字段。

但不是。除非由于范围命名冲突而需要消除歧义,否则您实际上不需要“this”。