gpt4 book ai didi

java - 访问外部类的字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:20 24 4
gpt4 key购买 nike

在给定对内部类对象的引用的情况下,如何访问外部类的字段?

class Outer
{
int field;

class Inner
{
void method(Inner parameter)
{
// working on the current instance is easy :)
field = 0;
Outer.this.field = 1;

// working on another instance is hard :(
parameter.field = 2; // does not compile
parameter.Outer.this.field = 3; // does not compile
parameter.outer().field = 4; // This works...
}

// ...but I really don't want to have to write this method!
Outer outer()
{
return Outer.this;
}
}
}

我还尝试了 Outer.parameter.field 和许多其他变体。是否有一种语法可以满足我的要求?

最佳答案

这个解决方案怎么样:

class Outer
{
int field;

class Inner
{
final Outer outer = Outer.this;
void method(Inner parameter)
{
// working on the current instance is easy :)
field = 0;
Outer.this.field = 1;

// working on another instance:
parameter.outer.field = 2;
}
}
}

关于java - 访问外部类的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6537082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com