在方法中使用“this”(在 Java 中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/516768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:40:59  来源:igfitidea点击:

Using "this" with methods (in Java)

javamethodsthis

提问by user42155

what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?

将“this”与 Java 中的方法一起使用怎么样?它是可选的还是在某些情况下需要强制使用它?

The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:

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

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

回答by Yes - that Jake.

I use "this" to clarify code, often as a hint that I'm calling an instance method rather than accessing a class-level method or a field.

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

But no. Unless disambiguation is required due to scope naming collision, you don't actually need "this."

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

回答by tvanfosson

The only time it is really required is when you have a parameter to a method with the same name as a member variable. Personally, I try to always use it to make the scope of the variable/method explicit. For example you could have a static method or an instance method. When reading the code it can be helpful to know which is which.

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

回答by Jon Skeet

Three obvious situations where you need it:

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

  • Calling another constructor in the same class as the first part of your constructor
  • Differentiating between a local variable and an instance variable (whether in the constructor or any other method)
  • Passing a reference to the current object to another method
  • 在与构造函数的第一部分相同的类中调用另一个构造函数
  • 区分局部变量和实例变量(无论是在构造函数中还是在任何其他方法中)
  • 将当前对象的引用传递给另一个方法

Here's an example of all three:

这是所有三个的示例:

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

I believe there are also some weird situations using inner classes where you need super.this.xbut they should be avoided as hugely obscure, IMO :)

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

EDIT: I can't think of any examples why you'd want it for a straight this.foo()method call.

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

EDIT: saua contributed this on the matter of obscure inner class examples:

编辑:saua 在模糊的内部类示例问题上做出了贡献:

I think the obscure case is: OuterClass.this.foo()when accessing foo()of the outer class from the code in an Inner class that has a foo()method as well.

我认为一个模糊的情况是:OuterClass.this.foo()foo()从内部类中的代码访问外部类时,该类也有一个foo()方法。

回答by Mike

For most general programing, the thiskeyword is optional and generally used to avoid confusion. However, there are a few places where it is needed.

对于大多数通用编程,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
}

These are not all the cases, but some of the more general ones. I hope this helps you better understand the thisand superkeywords and how/when to use them.

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

回答by Bill K

Not an answer (so feel free to vote it down), but I couldn't fit this into a comment where someone was asking.

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

A lot of people use "this.x" to visually differentiate instance variables from local variables and parameters.

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

So they would do this:

所以他们会这样做:

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

Personally I think it's a bad habit: any usable editor will put instance and local variables in a different color for you reliably--it doesn't require any human-fallible patterns.

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

Doing it with "this." is only 50% safe. Sure the compiler will catch it if you try to put this.x when x is a local variable, but there is nothing that is going to stop you from "Forgetting" to tag an instance variable with this., and if you forget to tag just one (or if someone else works on your code) and you are relying on the pattern, then the pattern may be more damaging than good

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

Personally I'm fairly sure the pattern stems from programmers (rightful) discomfort with the fact that in this case:

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

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

the fact that you need "this." in front of the me is determined by the name of the parameter--I agree it just feels sloppy. You want to be consistent--if you need this. in front of the me there, why not always use it?

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

Although I understand the discomfort, typing this. every single place that an instance variable is used is just pedantic, pointless, ugly and unreliable. If it really bothers you and you absolutely needto use a pattern to solve it, try the habit of putting "p" in front of your parameters. As a side effect, it should even make it more constant because the parameter case will now match the method case..

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

public void setMe( int pMe) 

回答by Steve Kuo

The only reason to prepend thisin 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.

this在方法调用前添加的唯一原因是表明您正在调用非静态方法。我想不出任何其他有效的理由来这样做(纠正我我错了)。我不推荐这个约定,因为它没有增加太多价值。如果没有一致地应用,那么它可能会产生误导(因为 this-less 方法调用仍然可能是非静态方法)。人们多久关心被调用的方法是否是静态的?此外,大多数 IDE 会以不同的方式突出显示静态方法。

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

我听说过这样的约定,其中this指示调用子类的方法,而没有this调用超类的方法。但这只是愚蠢的,因为惯例可能是相反的。

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

编辑:正如 mmyers 指出的(见评论),this使用静态方法。有了这个,我认为绝对没有理由在前面加上,this因为它没有任何区别。

回答by potyl

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

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

You absolutely need this if your method needs to return the object's instance.

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

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

This allows you to chain methods together in the following fashion:

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

String string = new StringBuildable()
    .append("hello")
    .append(' ')
    .append.("World")
    .toString()
;