内部类必须使用“this”吗?关键字以便使用外部类方法或属性?
我正在阅读 arraylist ,此类具有一个内部类,上面有名称sublist
。我正在以内部类的方法(sublist
)进行查看,并查看以下方法:
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
我看到该行3& 4使用此
关键字为了调用/使用arraylist
(outerallass)方法/属性。 我想了解的是必须使用outerClass.this
或elementData()
就足够了吗?我很久以前就运行了一个示例(一年多),并且我能够从内部类调用外部类方法,而无需使用this
关键字。
I'm reading the source code of ArrayList and this class has an inner class with the name SubList
. I'm looking in a method of the inner class (SubList
) and see the following methods:
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
What I see that line 3 & 4 uses this
keyword in order to call/use ArrayList
(outer class) method/attribute.
I want to understand is it must to use OuterClass.this
or elementData()
will be enough? I run an example long ago (more than a year) and I was able to call an outer class method from an inner class without using this
keyword.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个阴影问题,可能导致意外的行为和运行时错误。
如果特定范围(例如内部类或方法定义)中某种类型的声明(例如成员变量或参数名称或方法名称)的名称与封闭范围中的另一份声明相同,则声明阴影封闭范围的声明。您不能仅用其名称来指代阴影的声明。
输出:
如您所见,要获得更高范围的正确值,您需要仅使用
shadowtest.this
。通过时间,您的代码将突变,您可能会在另一个范围中错过相同的名称,因此您必须仅使用
oferclclass.toperclass.this
才能访问外部类范围,使代码清晰且防弹。参见 java tutorial 。
There is a Shadowing problem that can lead to unexpected behavior and runtime errors.
If a declaration of a type (such as a member variable or a parameter name or method name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope. You cannot refer to a shadowed declaration by its name alone.
Output:
As you can see, to get the correct value of higher scope, you need to use only
ShadowTest.this
.Thru time your code will mutate and you can miss the same name in the other scope, so you must use only
OuterClass.this
to access outer class scope, make code clear and bulletproof.See the Java Tutorial.