Java中的'this':它是如何工作的? [英] 'this' in Java: How does it work?

查看:120
本文介绍了Java中的'this':它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道'this'在Java中作为参考。我们只能在类成员中使用它。

I know that 'this' is acting as reference in Java. We can use it inside the class members only.

我要问的是......因为它在类的成员中使用,这意味着它必须是实例变量或参数。

What I am asking is... because it is used in the members of the class, that means it has to be either an instance variable or parameter.

并假设,如果它是方法的参数,但它在块中工作。 block不包含任何params和all ..你能解释一下它是什么...它在java中是如何定义的?它是如何使用By JVM的。

And assume, if it is param to a method but it is working in blocks. block does not contain any params and all ..could you explain what is it ...how exactly it was defined in java?How exactly it is using By JVM.

推荐答案

从语言学的角度来看,既不是局部变量也不是参数。从语法上讲,它是一个关键字。在语义上,它是一种表达当前对象的明确方式;请参阅 JLS 15.8.3 。例如:

From a linguistic point of view, this is neither a local variable or a parameter. Syntactically, it is a keyword. Semantically, it is an explicit way of saying "the current object"; see JLS 15.8.3. For example:


  • this。< attributeName> 显式引用实例级别当前对象的属性。

  • < methodName>(this)调用方法,将对当前对象的引用作为显式参数。

  • this.<attributeName> explicitly refers to an instance level attribute of the current object.
  • <methodName>(this) calls a method, passing a reference to the current object as an explicit argument.

关键字在Java中有其他用途t恰好表示当前对象:

The this keyword has other uses in Java that don't exactly mean "the current object":


  • this(< optArgumentList>)作为构造函数中的第一个语句链接到同一个类中的另一个构造函数; JLS 8.8.7

  • < className> .this 在内部类中引用当前对象的封闭类的实例; JLS 15.8.4

  • this(<optArgumentList>) as the first statement in a constructor chains to another constructor in the same class; JLS 8.8.7.
  • <className>.this within an inner class refers to the instance of an enclosing class for the current object; JLS 15.8.4.

从实施角度来看,您可以将this引用视为隐藏或每次调用实例方法时传递的隐式参数。实际上,这或多或少是JVM的invoke *字节码处理对象引用的方式。将目标对象引用推送到opstack后跟每个参数值,然后执行invoke ...指令。 (有关详细信息,请参阅此处。 )。

From an implementation perspective, you can think of the "this" reference as a hidden or implicit parameter that gets passed each time an instance method is called. Indeed, this is more or less how the object reference is treated by the JVM's "invoke*" bytecodes. You push the target object reference onto the "opstack" followed by each of the argument values, then execute the "invoke..." instruction. (Look here for the details.).

这篇关于Java中的'this':它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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