"this"的含义是什么?在Java中? [英] What is the meaning of "this" in Java?

查看:86
本文介绍了"this"的含义是什么?在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Normally, I use this in constructors only.

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

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的真正含义在Java中是什么,如果我使用不带点(.)的this会发生什么.

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

推荐答案

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

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


1
42
MyThisTest a=42

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

So effectively you use it for multiple things:

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

这篇关于"this"的含义是什么?在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆