Java中“ this”的含义是什么?


140

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

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

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



2
Yakshemash!太好了 您可能要参考这里我的问题,以及- stackoverflow.com/questions/23334336/... Chenqui。
Erran Morad 2014年

Answers:


157

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

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

1个
42
MyThisTest a = 42

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

  • 弄清楚您是在谈论一个字段,如果还有其他与该字段同名的东西
  • 整体引用当前对象
  • 在构造函数中调用当前类的其他构造函数

这不起作用。我收到一条错误消息,指出需要一种main方法。如果添加主方法,则必须从那里调用。而且任何在main内部调用frobnicate()的尝试都表示您不能从静态引用内部调用非静态引用。并且从中删除静态main变量会再次返回找不到主要方法的错误。请解释。
dbconfession

7
@dbconfession:这里的代码并不意味着是一个独立的,自运行的程序。你打算代码 文字,不运行它!它是有效的代码,但是仅用于演示目的(这就是为什么它没有适当的main的原因)。有关主要方法的帮助,请访问stackoverflow.com/questions/146576/…
Joachim Sauer 2014年

@Joachim谢谢!我缺少关于使方法静态化以及如何this.工作的基本知识。我的理解是,this.允许你调用一个方法或变量所特有的类的实例化版本,允许被称为而不调用方法或变量存在的另一个版本,this. 在一个简单的叫Test.class我有两种方法:public static void main()public Test() 我不能在方法之间传递信息,因为它main是静态的,并且构造函数不能设为静态。我应该发布为新问题吗?
dbconfession 2014年

@dbconfession:我觉得您的问题已经在其他地方回答了,但是我不太了解您的问题是什么,因此您最好将其发布(但准备将其作为重复项关闭)。但是,从最基本的角度讲,制作方法static基本上意味着您不需要类的实例来调用它,并且您将无法访问this它的内部。
Joachim Sauer 2014年

@JoachimSauer如果我想运行它,我该怎么办?我有与dbconfession相同的问题。
FudgeMuffins

52

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

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

以下是使用此方法的方法:

  1. 具体表示使用实例变量代替静态或局部变量。那是,

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

    这里指实例变量。在此,本地变量的优先级高。因此,缺少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!

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


44

要完整,this也可以用来引用外部对象

class Outer {
    class Inner {
        void foo() {
            Outer o = Outer.this;
    }
  }
}

5
this是我一直在寻找的东西!;)
forresthopkinsa

3
就是这样super
killjoy

18

它指的是特定对象的当前实例,因此您可以编写如下内容

public Object getMe() {
    return this;
}

的常见用例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;
    }
}

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

public class Person {
    private final String name;

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

4
调用时请小心使用正确的样式:o.getMe()。getMe()。outOfHere()
Justin K 2010年

8

在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!");
    }

}

7

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

System.out.println(this);

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


7

引用programming.guide上的文章


this在Java程序中有两个用途

1.作为对当前对象的参考

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

this.someVariable = someVariable;

此处描述了这种使用方式:“ this”参考(包含示例)

2.调用其他构造函数

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

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

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

此处描述了这种使用方式:this(…)构造函数调用(带有示例)


4

它指的是在其上调用该方法的实例

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

4

这个关键字被用于指代一个块的当前可变的,例如考虑下面的代码(只是一exampple,所以不要指望标准Java代码):

Public class test{

test(int a) {
this.a=a;
}

Void print(){
System.out.println(a);
}

   Public static void main(String args[]){
    test s=new test(2);
    s.print();
 }
}

而已。输出将为“ 2”。如果我们不使用this关键字,那么输出将为:0


3

对象具有从类派生的方法和属性(变量),以便指定this使用保留字的方法和变量属于特定对象。对于实例变量,了解隐式和显式参数之间的区别很重要。看一下fillTankaudi对象的调用。

Car audi= new Car();

audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter 

括号中的值是隐式参数,对象本身是显式参数,没有显式参数的fillTank方法使用隐式参数,该方法同时具有显式和隐式参数。

让我们仔细看看该类中的fillTank方法Car

public class Car()
{
   private double tank;

   public Car()
   {
      tank = 0;
   }

   public void fillTank(double gallons)
   {
      tank = tank + gallons;
   }

}

在此类中,我们有一个实例变量“ tank”。为了指定将实例变量“ tank”用于特定对象,可能有许多对象使用tank实例变量,在我们前面的示例中,我们使用“ thisreserved”关键字来指定实例对象“ tank” 。对于实例变量,在方法中使用“ this” 表示实例变量(在我们的示例中为“ tank”)是隐式参数的实例变量。

Java编译器会自动添加this保留字,因此您不必添加保留字,这是优先选择的问题。this没有dot(。)不能使用,因为这是java的规则(语法)。

综上所述。

  • 对象由类定义,并具有方法和变量
  • 使用this上的实例变量中的一个方法表明,该实例变量属于隐式参数,或者说,它是隐式参数的一个实例变量。
  • 隐式参数是在这种情况下从“ audi”调用该方法的对象。
  • Java编译器会自动添加此保留字,添加是优先选择的问题
  • this 没有点号(。)不能使用,这在语法上是无效的
  • this 也可以用来区分名称相同的局部变量和全局变量
  • this保留字也适用于方法,以指示一个方法,属于一个特定的对象。

2

实例变量对于您创建的每个对象都是通用的。说,有两个实例变量

class ExpThisKeyWord{
int x;
int y;

public void setMyInstanceValues(int a, int b) {
    x= a;
    y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

}




class Demo{
public static void main(String[] args){

ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();

obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);



}
}

如果您注意到上面的代码,我们已经启动了三个对象,并且三个对象正在调用SetMyInstanceValues方法。您认为JVM如何为每个对象正确分配值?有个窍门,JVM不会看到上面显示的代码。取而代之的是,它看起来像下面的代码;

public void setMyInstanceValues(int a, int b) {
    this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
    this.y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

2

(我知道我晚了,但嘘我是你从未见过我的偷偷摸摸的家伙)

如果不是全部,则在大多数面向对象的编程语言中关键字表示对该类的当前对象实例的引用。本质上与从名称外部从方法外部调用该对象相同。这可能没有任何意义,因此我将详细说明:

在类之外,为了在对象的该实例内调用某些内容,例如说您有一个名为object的对象,并且想要获得一个字段,则需要使用该字段

object.field

假设您正在尝试从类内部访问object.field,例如,您的构造函数,则可以使用

this.field

在类内部被调用时,this关键字本质上替代了object name关键字。如果您有两个同名的变量,其中一个是类的一个字段,另一个是方法内部的一个变量,通常没有太多理由这样做,这有助于在两个变量之间进行解密。例如,如果您有以下内容:((嗯,明白吗?这个?呵呵...。只是我?)好吧:(我现在就离开)

public String Name;
//Constructor for {object} class
public object(String Name){
    Name = Name;
}

这将导致一些问题,编译器将无法知道在构造函数的参数中定义的Name变量与类的字段声明内的Name变量之间的区别,因此它将向其分配Name参数。 .. Name参数的值,该值无济于事,字面上没有任何用途。这是大多数较新的程序都常见的问题,我也是其中的受害者。无论如何,定义此参数的正确方法是使用:

public String Name;
//Constructor for {object} class
public object(String Name){
    this.Name = Name;
}

这样,编译器知道您要分配的Name变量是类的一部分,而不是方法的一部分,并正确分配了它,这意味着它将把Name字段分配给您放入构造函数中的任何内容。

概括起来,它实质上引用了您正在处理的类的对象实例的字段,因此它是关键字“ this”,表示其this对象或this实例。最好在调用类的字段时使用此方法,而不仅仅是使用名称以避免编译器直接在其上运行时难以发现的可能的错误。





1

这是指您当前所在的对象。换句话说,这是指接收对象。您可以使用它来澄清您所指的是哪个变量。Java_whitepaper页面:37

class Point extends Object
{
    public double x;
    public double y;

    Point()
    {
        x = 0.0;
        y = 0.0;
    }

    Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
}

在上面的示例代码中,this.x / this.y引用当前类,即Point类x和y变量,其中(double x,double y)是从不同类传递来将值分配给当前类的double值。


0

我也在寻找相同的答案,但不知为何无法清楚地理解这个概念。但是最后我从这个链接了解了

这是Java中的关键字。可以在类的方法或构造函数中使用。它(此)作为对当前对象的引用,该对象的方法或构造函数正在被调用。此关键字可用于从实例方法或构造函数中引用当前对象的任何成员。

检查链接中的示例以获得清晰的理解


完美的例子
sathya '18

0

如果实例变量与构造函数中声明的变量相同,则使用“ this”分配数据。

class Example{
     int assign;// instance variable

     Example(int assign){ // variable inside constructor
          this.assign=assign;
     }
}

希望这可以帮助。


0

在Java中,“ this”是预定义的变量。如果在方法中使用“ this”,则意味着我们正在获取当前正在运行的对象的引用(地址)。举个例子。

this.age --->当前运行对象的年龄。


0

我想分享一下我对这个关键字的理解。此关键字在Java中有6种用法,如下所示:

1.可用于引用当前类变量。 让我们用代码来理解。*

如果不通过以下示例使用此关键字,让我们了解问题:

class Employee{  
int id_no;  
String name;  
float salary;  
Student(int id_no,String name,float salary){  
id_no = id_no;  
name=name;  
salary = salary;  
}  
void display(){System.out.println(id_no +" "+name+" "+ salary);}  
}  
class TestThis1{  
public static void main(String args[]){  
Employee s1=new Employee(111,"ankit",5000f);  
Employee s2=new Employee(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

输出:-

0 null 0.0
0 null 0.0

在上面的示例中,参数(形式参数)和实例变量相同。因此,我们使用此关键字来区分局部变量和实例变量。

class Employee{  
int id_no;  
String name;  
float salary;  
Student(int id_no,String name,float salary){  
this.id_no = id_no;  
this.name=name;  
this.salary = salary;  
}  
void display(){System.out.println(id_no +" "+name+" "+ salary);}  
}  
class TestThis1{  
public static void main(String args[]){  
Employee s1=new Employee(111,"ankit",5000f);  
Employee s2=new Employee(112,"sumit",6000f);  
s1.display();  
s2.display();  
}} 

输出:

111 ankit 5000
112 sumit 6000

2.调用当前的类方法。

class A{  
void m(){System.out.println("hello Mandy");}  
void n(){  
System.out.println("hello Natasha");  
//m();//same as this.m()  
this.m();  
}  
}  
class TestThis4{  
public static void main(String args[]){  
A a=new A();  
a.n();  
}}  

输出:

hello Natasha
hello Mandy

3.调用当前类的构造函数。它用于构造函数链接。

class A{  
A(){System.out.println("hello ABCD");}  
A(int x){  
this();  
System.out.println(x);  
}  
}  
class TestThis5{  
public static void main(String args[]){  
A a=new A(10);  
}}

输出:

hello ABCD
10

4.在方法中作为参数传递。

class S2{  
  void m(S2 obj){  
  System.out.println("The method is invoked");  
  }  
  void p(){  
  m(this);  
  }  
  public static void main(String args[]){  
  S2 s1 = new S2();  
  s1.p();  
  }  
}  

输出:

The method is invoked

5.在构造函数调用中作为参数传递

class B{  
  A4 obj;  
  B(A4 obj){  
    this.obj=obj;  
  }  
  void display(){  
    System.out.println(obj.data);//using data member of A4 class  
  }  
}  

class A4{  
  int data=10;  
  A4(){  
   B b=new B(this);  
   b.display();  
  }  
  public static void main(String args[]){  
   A4 a=new A4();  
  }  
} 

输出:-

10

6.返回当前的类实例

class A{  
A getA(){  
return this;  
}  
void msg(){System.out.println("Hello");}  
}  
class Test1{  
public static void main(String args[]){  
new A().getA().msg();  
}  
}  

输出:-

Hello

另外,如果没有。(dot),则不能使用此关键字,因为其语法无效。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.