20

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

4

12 回答 12

38

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

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

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

我的手臂或腿

认为this只是一种类型说“我的”的方式。所以一个伪代码表示看起来像这样:

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        my.bar = bar;
    }
}
于 2009-02-23T13:14:09.687 回答
21

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

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

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

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

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

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

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

public class MyClass
{
    String name;

    public class MyClass
    {
        String name;

        public String getOuterName()
        {
            return MyClass.this.name;
        }
    }
}
于 2009-02-23T13:34:53.503 回答
6

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

在此处查看详细信息

于 2009-02-23T13:13:55.350 回答
6

关键字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";
    }

}

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

public class ProperExample {
    private int numberOfExamples;

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

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

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

于 2009-02-23T13:16:42.050 回答
4

更好地利用这个

public class Blah implements Foo {

   public Foo getFoo() {
      return this;
   }
}

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

public class Blah {

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

你怎么能做这些操作。

于 2009-02-23T13:16:25.797 回答
2

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

例子 ::

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.
    }
}
于 2013-05-10T09:35:30.030 回答
1

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

此外,从“这个和超级”:

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

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

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

于 2009-02-23T13:27:37.640 回答
1

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

public class A{
    int attr=10;

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

}//end class A

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

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

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

于 2009-02-23T13:37:59.817 回答
1

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

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);
    }
  }
}
于 2009-02-23T13:51:48.613 回答
0

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

WindowMaker foo = new WindowMaker(this);

例如,您当前位于从 JFrame 扩展的类中,并且您希望为 JFrame 传递对 WindowMaker 对象的引用,以便它可以与 JFrame 交互。您可以通过将 JFrame 的引用传递给名为“this”的对象来传递对 JFrame 的引用。

于 2009-02-23T13:30:22.393 回答
0

每个对象都可以使用关键字 this 访问对自身的引用(有时称为 this 引用)。

首先让我们看一下代码

public class Employee  {

private int empId;
private String name;

public int getEmpId() {
    return this.empId;
}

public String getName() {
    return this.name;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public void setName(String name) {
    this.name = name;
}

}

在上述方法中 getName() 返回实例变量名。现在让我们再看看类似的代码是

public class Employee  {

private int empId;
private String name;

public int getEmpId() {
    return this.empId;
}

public String getName() {

    String name="Yasir Shabbir";
    return name;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public void setName(String name) {
    this.name = name;
}


public static void main(String []args){
    Employee e=new Employee();
    e.setName("Programmer of UOS");

    System.out.println(e.getName());

}

}

输出 Yasir Shabbir

  • 此运算符始终与实例变量(属于对象)而不是任何类变量(属于类)一起使用
  • 这总是指类非静态属性而不是任何其他参数或局部变量。
  • 这总是在非静态方法中使用
  • 该运算符不能用于静态变量(类变量)

**注意:**当方法包含与类的字段同名的参数或局部变量时,通常是逻辑错误。在这种情况下,如果您希望访问类的字段,请使用引用 this - 否则将引用方法参数或局部变量。

于 2014-07-26T11:30:49.050 回答
0

'this' 的作用非常简单。它保存当前对象的引用。

  • 此关键字保存当前类实例的引用
  • 此关键字不能在静态函数或静态块中使用
  • 该关键字可用于访问实例的阴影变量
  • 此关键字可用于在函数调用中将当前对象作为参数传递
  • 该关键字可用于创建构造函数链

来源:http: //javaandme.com/core-java/this-word

于 2015-10-10T18:09:00.143 回答