Java中的“this”是什么意思?

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

What is the meaning of "this" in Java?

java

提问by guilgamos

Normally, I use thisin constructors only.

通常,我this只在构造函数中使用。

I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.

我知道它用于标识参数变量(通过使用this.something),如果它与全局变量具有相同的名称。

However, I don't know that what the real meaning of thisis in Java and what will happen if I use thiswithout dot (.).

但是,我不知道thisJava 中的真正含义是什么,如果我this不使用点 ( .)会发生什么。

回答by Jon Freedman

It refers to the current instance of a particular object, so you could write something like

它指的是特定对象的当前实例,因此您可以编写类似

public Object getMe() {
    return this;
}


A common use-case of thisis to prevent shadowing. Take the following example:

的一个常见用例this是防止阴影。以下面的例子为例:

public class Person {
    private final String name;

    public Person(String name) {
        // how would we initialize the field using parameter?
        // we can't do: name = name;
    }
}

In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. thisallows us to access members of this instance, including the field.

在上面的例子中,我们想使用参数的值来分配字段成员。由于它们共享相同的名称,我们需要一种方法来区分字段和参数。this允许我们访问此实例的成员,包括字段。

public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }
}

回答by Jon Skeet

It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:

它实际上是“对当前上下文中对象的引用”。例如,要打印出“这个对象”,你可以这样写:

System.out.println(this);

Note that your usage of "global variable" is somewhat off... if you're using this.variableNamethen by definition it's nota global variable - it's a variable specific to this particular instance.

请注意,您对“全局变量”的使用有些偏离……如果您正在使用,this.variableName那么根据定义,它不是全局变量 - 它是特定于该特定实例的变量。

回答by Albinoswordfish

A quick google search brought this result: http://xahlee.org/java-a-day/this.html

一个快速的谷歌搜索带来了这个结果:http: //xahlee.org/java-a-day/this.html

Pretty much the "this" keyword is a reference to the current object (itself).

几乎“this”关键字是对当前对象(本身)的引用。

回答by Behrang Saeedzadeh

回答by Dheeraj Joshi

this can be used inside some method or constructor.

这可以在某些方法或构造函数中使用。

It returns the reference to the current object.

它返回对当前对象的引用。

回答by Bart van Heukelom

It refers to the instance on which the method is called

它指的是调用方法的实例

class A {

  public boolean is(Object o) {
    return o == this;
  }

}

A someA = new A();
A anotherA = new A();
someA.is(someA); // returns true
someA.is(anotherA); // returns false

回答by Joachim Sauer

thisrefers to the current object.

this指向当前对象。

Each non-static method runs in the context of an object. So if you have a class like this:

每个非静态方法都在对象的上下文中运行。因此,如果您有这样的课程:

public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

Then calling frobnicate()on new MyThisTest()will print

然后调用frobnicate()new MyThisTest()会打印

1
42
MyThisTest a=42

So effectively you use it for multiple things:

因此,您可以有效地将它用于多种用途:

  • clarify that you are talking about a field, when there's also something else with the same name as a field
  • refer to the current object as a whole
  • invoke other constructors of the current class in your constructor
  • 澄清您正在谈论一个字段,当还有其他与字段同名的内容时
  • 整体引用当前对象
  • 在构造函数中调用当前类的其他构造函数

回答by Qwerky

In Swing its fairly common to write a class that implements ActionListenerand add the current instance (ie 'this') as an ActionListener for components.

在 Swing 中,编写一个类来实现ActionListener并将当前实例(即“this”)添加为组件的 ActionListener 是相当常见的。

public class MyDialog extends JDialog implements ActionListener
{
    public MyDialog()
    {
        JButton myButton = new JButton("Hello");
        myButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Hurdy Gurdy!");
    }

}

回答by MicSim

The following is a copy & paste from here, but explains very well all different uses of the thiskeyword:

以下是从这里复制和粘贴的内容,但很好地解释了this关键字的所有不同用法:

Definition: Java's thiskeyword is used to refer the current instance of the method on which it is used.

定义:Java 的this关键字用于引用使用它的方法的当前实例。

Following are the ways to use this:

以下是使用它的方法:

  1. To specifically denote that the instance variable is used instead of static or local variable. That is,

    private String javaFAQ;
    void methodName(String javaFAQ) {
        this.javaFAQ = javaFAQ;
    }
    

    Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the thisdenotes the local variable. If the local variable that is parameter's name is not same as instance variable then irrespective of thisis used or not it denotes the instance variable.

  2. Thisis used to refer the constructors

     public JavaQuestions(String javapapers) {
         this(javapapers, true);
     }
    

    This invokes the constructor of the same java class which has two parameters.

  3. Thisis used to pass the current java instance as parameter

    obj.itIsMe(this);
    
  4. Similar to the above this can also be used to return the current instance

    CurrentClassName startMethod() {
         return this;
    }
    

    Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.

  5. Thiscan be used to get the handle of the current class

    Class className = this.getClass(); // this methodology is preferable in java
    

    Though this can be done by

    Class className = ABC.class; // here ABC refers to the class name and you need to know that!
    
  1. 具体表示使用实例变量代替静态或局部变量。那是,

    private String javaFAQ;
    void methodName(String javaFAQ) {
        this.javaFAQ = javaFAQ;
    }
    

    这里 this 指的是实例变量。这里局部变量的优先级很高。因此,缺少this表示局部变量。如果作为参数名称的局部变量与实例变量不同,则无论this是否使用它都表示实例变量。

  2. This用于引用构造函数

     public JavaQuestions(String javapapers) {
         this(javapapers, true);
     }
    

    这将调用具有两个参数的同一个 java 类的构造函数。

  3. This用于将当前java实例作为参数传递

    obj.itIsMe(this);
    
  4. 与上面类似,这也可以用于返回当前实例

    CurrentClassName startMethod() {
         return this;
    }
    

    注意:在以上两点的内部类中使用时,这可能会导致不希望的结果。因为这将引用内部类而不是外部实例。

  5. This可用于获取当前类的句柄

    Class className = this.getClass(); // this methodology is preferable in java
    

    虽然这可以通过

    Class className = ABC.class; // here ABC refers to the class name and you need to know that!
    

As always, thisis associated with its instance and this will not work in static methods.

与往常一样,this与其实例相关联,这在静态方法中不起作用。

回答by aioobe

Quoting an articleat programming.guide:

引用programming.guide上的一篇文章



thishas two usesin a Java program.

this在 Java 程序中有两个用途

1. As a reference to the current object

1.作为对当前对象的引用

The syntax in this case usually looks something like

这种情况下的语法通常看起来像

this.someVariable = someVariable;

This type of use is described here: The 'this' reference (with examples)

此处描述了这种类型的使用:“this”参考(带有示例)

2. To call a different constructor

2. 调用不同的构造函数

The syntax in this case typically looks something like

这种情况下的语法通常看起来像

MyClass() {
    this(DEFAULT_VALUE); // delegate to other constructor
}

MyClass(int value) {
    // ...
}

This type of use is described here: this(…) constructor call (with examples)

此处描述了这种类型的使用:this(...) 构造函数调用(带有示例)