18

在 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;
    }
}
4

7 回答 7

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;
    }
}

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

编辑:我想不出任何示例,为什么您希望将其用于直接的this.foo()方法调用。

编辑: saua 就晦涩的内部类示例做出了贡献:

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

于 2009-02-05T16:55:34.910 回答
3

我使用“this”来澄清代码,通常作为我正在调用实例方法而不是访问类级别方法或字段的提示。

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

于 2009-02-05T16:54:21.060 回答
3

对于大多数通用编程,this关键字是可选的,通常用于避免混淆。但是,有几个地方需要它。

class Foo {
    int val;

    public Foo(int val) {
         this(val, 0);  //this MUST be here to refer to another constructor
    }

    public Foo(int val, int another) {
        val = val;       //this will work, but it generally not recommended.
        this.val = val;  //both are the same, but this is more useful.
        method1();       //in a Foo instance, it will refer to this.method1()
        this.method1();  //but in a Foo2 instance, you must use this to do the same
    }

    public void method1() {}
}

class Foo2 extends Foo {
    public Foo2(int val) {
        this(val);        //this will refer to the other Foo2 constructor
    }
    public Foo2(int val, int another) {
        super(val, another);
        super.method1();   //this will refer to Foo.method1()
    }

    @Override
    public void method1() {}//overridden method
}

这些不是所有情况,而是一些更普遍的情况。我希望这可以帮助您更好地理解thissuper关键字以及如何/何时使用它们。

于 2009-02-05T17:04:20.463 回答
0

唯一真正需要的情况是当您有一个与成员变量同名的方法的参数时。就个人而言,我尝试始终使用它来明确变量/方法的范围。例如,您可以有一个静态方法或一个实例方法。阅读代码时,知道哪个是哪个会很有帮助。

于 2009-02-05T16:54:56.050 回答
0

The only reason to prepend this in front of a method invocation is to indicate that you're calling a non-static method. I can't think of any other valid reason to do this (correct me I'm wrong). I don't recommend this convention as it doesn't add much value. If not applied consistently then it could be misleading (as a this-less method invocation could still be a non-static method). How often does one care if the method being invoked is static or not? Furthermore, most IDEs will highlight static methods differently.

I have heard of conventions where this indicates calling the subclass's method while an absence of this is calling the super class's method. But this is just silly as the convention could be the other way around.

Edit: As mmyers points out (see comment), this works with static methods. With that, I see absolutely no reason to prepend with this as it doesn't make any difference.

于 2009-02-11T19:26:49.950 回答
0

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html

如果您的方法需要返回对象的实例,您绝对需要这个。

public class StringBuildable {
    public StringBuildable append(String text) {
        // Code to insert the string -- previously this.internalAppend(text);
        return this;
    }
}

这允许您以以下方式将方法链接在一起:

String string = new StringBuildable()
    .append("hello")
    .append(' ')
    .append.("World")
    .toString()
;
于 2009-02-11T20:01:16.420 回答
0

不是答案(所以请随意投反对票),但我无法将其放入有人询问的评论中。

很多人使用“this.x”来直观地区分实例变量与局部变量和参数。

所以他们会这样做:

private int sum;
public int storeSquare (int b) {
    int c=b*b;
    this.sum+=c; // Makes sum "pop" I guess
    return c;
}

我个人认为这是一个坏习惯:任何可用的编辑器都会可靠地将实例和局部变量设置为不同的颜色——它不需要任何人为错误的模式。

用“这个”来做。只有 50% 的安全。如果您尝试在 x 是局部变量时放置 this.x,则编译器肯定会捕获它,但是没有什么可以阻止您“忘记”用 this 标记实例变量,并且如果您忘记标记只有一个(或者如果其他人在您的代码上工作)并且您依赖于该模式,那么该模式可能弊大于利

就我个人而言,我相当确定这种模式源于程序员(正当)对以下事实感到不适:

public void setMe(int me) {
    this.me=me;
}

你需要“这个”的事实。在我面前是由参数的名称决定的——我同意它只是感觉草率。你想要保持一致——如果你需要的话。在我面前有,为什么不经常使用呢?

虽然我理解这种不适,但打字。使用实例变量的每一个地方都是迂腐的、毫无意义的、丑陋的和不可靠的。如果它真的困扰您并且您绝对需要使用模式来解决它,请尝试将“p”放在参数前面的习惯。作为副作用,它甚至应该使其更加恒定,因为参数 case 现在将匹配方法 case..

public void setMe( int pMe) 
于 2009-02-05T18:47:12.580 回答