在java中使用关键字“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/577575/
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 16:26:43  来源:igfitidea点击:

Using the keyword "this" in java

javakeyword

提问by BloodParrot

I'm trying to get an understanding of what the the java keyword thisactually does. I've been reading Sun's documentation but I'm still fuzzy on what thisactually does.

我试图了解 java 关键字的this实际作用。我一直在阅读 Sun 的文档,但我仍然不清楚this实际做什么。

采纳答案by Andrew Hare

The thiskeyword is a reference to the current object.

this关键字是对当前对象的引用。

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        // the "this" keyword allows you to specify that
        // you mean "this type" and reference the members
        // of this type - in this instance it is allowing
        // you to disambiguate between the private member
        // "bar" and the parameter "bar" passed into the
        // constructor
        this.bar = bar;
    }
}

Another way to think about it is that the thiskeyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Meand the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.

另一种思考方式是,this关键字就像您用来指代自己的人称代词。其他语言对同一概念有不同的词。VB 使用Me和 Python 约定(因为 Python 不使用关键字,只是每个方法的隐式参数)是使用self.

If you were to reference objects that are intrinsically yours you would say something like this:

如果你要引用本质上属于你的对象,你会说这样的话:

Myarm or myleg

我的手臂或我的

Think of thisas just a way for a type to say "my". So a psuedocode representation would look like this:

将其this视为一种类型说“我的”的方式。因此,伪代码表示如下所示:

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        my.bar = bar;
    }
}

回答by Otávio Décio

"this" is a reference to the current object.

“this”是对当前对象的引用。

See details here

在此处查看详细信息

回答by ng.

An even better use of this

更好地利用这个

public class Blah implements Foo {

   public Foo getFoo() {
      return this;
   }
}

It allows you to specifically "this" object in the current context. Another example:

它允许您在当前上下文中专门“这个”对象。另一个例子:

public class Blah {

   public void process(Foo foo) { 
      foo.setBar(this);
   }
}

How else could you do these operations.

你还能怎么做这些操作。

回答by Spoike

The keyword thisis a reference to the current object. It's best explained with the following piece of code:

关键字this是对当前对象的引用。最好用以下代码来解释:

public class MyClass {

    public void testingThis() 
    {
        // You can access the stuff below by 
        // using this (although this is not mandatory)

        System.out.println(this.myInt);
        System.out.println(this.myStringMethod());

        // Will print out:
        // 100
        // Hello World
    }

    int myInt = 100;
    string myStringMethod() 
    {
        return "Hello World";
    }

}

It's not used a lot unless you have code standard at your place telling you to use the thiskeyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:

除非您的地方有代码标准告诉您使用this关键字,否则它不会经常使用。它有一个常见用途,那就是如果您遵循代码约定,其中参数名称与类属性相同:

public class ProperExample {
    private int numberOfExamples;

    public ProperExample(int numberOfExamples) 
    {
        this.numberOfExamples = numberOfExamples;
    }
}

One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):

this 关键字的一种正确用法是链接构造函数(使构造对象在整个构造函数中保持一致):

public class Square {
    public Square() 
    {
        this(0, 0);
    }

    public Square(int x_and_y) 
    {
        this(x_and_y, x_and_y);
    }

    public Square(int x, int y)
    {
       // finally do something with x and y
    }
}

This keyword works the same way in e.g. C#.

该关键字在例如 C# 中的工作方式相同。

回答by Joe Liversedge

The keyword 'this' refers to the current object's context. In many cases (as Andrewpoints out), you'll use an explicit thisto make it clear that you're referring to the current object.

关键字“ this”指的是当前对象的上下文。在许多情况下(正如Andrew指出的那样),您将使用显式this来明确表示您指的是当前对象。

Also, from 'this and super':

另外,从'这个和超级':

*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.

*还有其他用途。有时,在编写实例方法时,需要将包含该方法的对象作为实际参数传递给子程序。在这种情况下,您可以将其用作实际参数。例如,如果您想打印出对象的字符串表示形式,您可以说“System.out.println(this);”。或者您可以在赋值语句中将 this 的值赋给另一个变量。

In fact, you can do anything with this that you could do with any other variable, except change its value.*

事实上,你可以用它做任何你可以用任何其他变量做的事情,除了改变它的值。*

That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.

该站点还引用了“ super”的相关概念,这可能有助于理解这些如何与继承一起工作。

回答by Kyle G

Think of it in terms of english, "this object" is the object you currently have.

用英语来思考,“这个对象”是你当前拥有的对象。

WindowMaker foo = new WindowMaker(this);

For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".

例如,您当前位于从 JFrame 扩展的类中,并且您想要传递对 JFrame 的 WindowMaker 对象的引用,以便它可以与 JFrame 交互。您可以传递对 JFrame 的引用,方法是将其引用传递给名为“this”的对象。

回答by Michael Borgwardt

The keyword thiscan mean different things in different contexts, that's probably the source of your confusion.

关键字this在不同的上下文中可能意味着不同的东西,这可能是您混淆的根源。

It can be used as a object reference which refers to the instance the current method was called on: return this;

它可以用作对象引用,引用当前方法被调用的实例: return this;

It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:

它可以用作引用当前构造函数正在创建的实例的对象引用,例如访问隐藏字段:

MyClass(String name)
{
    this.name = name;
}

It can be used to invoke a different constructor of a a class from within a constructor:

它可用于从构造函数中调用 aa 类的不同构造函数:

MyClass()
{
    this("default name");
}

It can be used to access enclosing instances from within a nested class:

它可用于从嵌套类中访问封闭实例:

public class MyClass
{
    String name;

    public class MyClass
    {
        String name;

        public String getOuterName()
        {
            return MyClass.this.name;
        }
    }
}

回答by alepuzio

It's a reference of actual instance of a class inside a method of the same class. coding

它是同一个类的方法内一个类的实际实例的引用。编码

public class A{
    int attr=10;

    public int calc(){
     return this.getA()+10;
   }
   /**
   *get and set
   **/    

}//end class A

In calc()body, the software runs a method inside the object allocated currently.

calc()主体中,软件在当前分配的对象内部运行一个方法。

How it's possible that the behaviour of the object can see itself? With the thiskeyword, exactly.

对象的行为怎么可能看到自己?使用this关键字,完全正确。

Really, the thiskeyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.

确实,this关键字不需要强制使用(如super),因为 JVM 知道在哪里调用内存区域中的方法,但在我看来,这使代码更具可读性。

回答by PhiLho

It can be also a way to access information on the current context. For example:

它也可以是访问当前上下文信息的一种方式。例如:

public class OuterClass
{
  public static void main(String[] args)
  {
    OuterClass oc = new OuterClass();
  }

  OuterClass()
  {
    InnerClass ic = new InnerClass(this);
  }

  class InnerClass
  {
    InnerClass(OuterClass oc)
    {
      System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
      System.out.println("This class: " + this + " / " + this.getClass());
      System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
      System.out.println("Other way to parent: " + OuterClass.this);
    }
  }
}

回答by Priyanka Vishwakarma

"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.

“this”关键字指的是由于该方法正在执行的当前对象。它还用于避免在方法中作为参数传递的局部变量与实例变量之间的歧义,只要实例变量和局部变量具有相同的名称。

Example ::

例子 ::

public class ThisDemo1 
{
    public static void main(String[] args) 
   {
        A a1=new A(4,5);       
   }
}

class A
{
    int num1;
    int num2;

    A(int num1)
    {
        this.num1=num1; //here "this" refers to instance variable num1. 
       //"this" avoids ambigutiy between local variable "num1" & instance variable "num1"

        System.out.println("num1 :: "+(this.num1));
    }

    A(int num, int num2)
    {
        this(num); //here "this" calls 1 argument constructor within the same class.
        this.num2=num2;
        System.out.println("num2 :: "+(this.num2)); 
       //Above line prints value of the instance variable num2.
    }
}