java是否可以从嵌套类引用outter类指针?
我需要在内部类中使用外部类的this
指针
我不知道如何在不保存this
指针的情况下进行操作。还有别的选择吗
class outerclass {
outerClass thisPointer;
outerclass () {
//
// NOTE: I am saving this pointer here to reference
// by the inner class later. I am trying to find
// a different alternative instead of saving this pointer.
//
thisPointer = this;
}
class innerClass {
void doSomething () {
//
// is there a way to reference the outter class
// without having to save the thisPointer from
// the outter class.
// NOTE someObject is a class outside of the
// outterclass control.
//
someObject.someMethod (thisPointer);
}
}
}
# 1 楼答案
使用语法
NameOfOuterClass.this
:# 2 楼答案
我们应该做到这一点
我假设你的外部类名是outerclass。按照Java的惯例,类名应该以大写字母开头
如果我没有正确理解你的例子,那么这里有一些示例代码。这里,外部类(Test1)中a的值被分配给内部类(Test2)中的局部变量