[英]How does an explicitly scoped this keyword in java work?
I know this
key word is used to point to current class fields and to call constructor like: 我知道this
关键字用于指向当前的类字段并像这样调用构造函数:
class A{
String name;
public A(String name)
{
this.name=name;
this.(name.length());
}
public(int len)
{
//some code here
}
}
but my I recently came across: 但我最近遇到了:
class B extends A
{
A varA = B.this;
}
I don't understand how B.this works. 我不明白这是怎么工作的。 can any one elaborate in detail 谁能详细说明一下
B.this
is a reference to B
class instance. B.this
是对B
类实例的引用。
as B
extends A
it is possible to declare a variable of type A
and assign it to a reference to B
class instance. 随着B
扩展A
,可以声明类型A
的变量并将其分配给对B
类实例的引用。
In the example you have, B.this
is equivalent to this
, so it's not very illustrative. 在您的示例中, B.this
等效于this
,因此它不是非常说明性的。 Scoped this
declarations are far more valuable when you start working with inner classes.... 当您开始使用内部类时, this
声明更有价值。
class Outer {
public void doSomething() {
}
class Inner {
public void doSomething() {
Outer.this.doSomething();
}
}
}
Notice the use of Outer.this
in the Inner
class. 注意Inner
类中Outer.this
的使用。 Without it, the inner class would have no way of disambiguating between the this
that referred to the Inner instance and the this
that referred to the Outer instance. 没有它,内部类就没有之间消除歧义的方式this
是指内在实例和this
是指外实例。
The B.this
means that you are getting the reference/pointer of the B class instance, B inherits from A so what you are actually doing is Initializing your A with the reference/pointer of B . B.this
意味着您正在获取B类实例的引用/指针, B继承自A,因此您实际要做的是使用B的引用/指针初始化A。
The B.this
is useful when you are calling the instance of B class
inside a anonymous/inner
classes. 当您在anonymous/inner
类中调用B class
的实例时, B.this
很有用。
You can also call this
which is equivalent to B.this
but you cant call this
in a anonymous/inner
classes or else you'll get the instance of them not the class B
instance. 您也可以调用this
,它等效于B.this
但是您不能在anonymous/inner
类中调用this
,否则您将得到它们的实例而不是class B
实例。
In fact, the this
keyword is used to refer to the instance of a class. 实际上, this
关键字用于引用类的实例。
When you do 当你做
this.name
you are referring to the attribute name
from the actual instance of the class A
. 您是从类A
的实际实例中引用属性name
。
When you do 当你做
B.this
you are referring to the B
class intance. 您指的是B
级实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.