Is it possible for the nested inner classes ABar and BBar to access main class's variables? For example:
嵌套内部类ABar和BBar是否可能访问主类的变量?例如:
public class Foo {
public ABar abar = new ABar();
public BBar bbar = new BBar();
public int someCounter = 0;
public class ABar {
public int i = 0;
public void someMethod(){
i++;
someCounter++;
}
}
public class BBar {
public void anotherMethod(){
bbar.someMethod();
someCounter++;
}
}
}
// then called using: //
Foo myFoo = new Foo();
myFoo.bbar.anotherMethod();
Edit
编辑
Seems the code I typed would have worked if i'd have tried it first; was trying to get help without being too specific. The code I'm actually having trouble with
如果我先试一下的话,我输入的代码就会正常工作;我想要得到帮助,但又不太具体。我的代码有问题
Fails because of the error 'cannot make static reference to the non-static field stage'
由于错误“无法对非静态字段级进行静态引用”而失败
public class Engine {
public Stage stage = new Stage();
// ...
public class Renderer implements GLSurfaceView.Renderer {
// ...
@Override
public void onDrawFrame(GL10 gl) {
stage.alpha++;
}
}
public class Stage extends MovieClip {
public float alpha = 0f;
}
2 个解决方案
#1
18
In your code, yes, it is possible.
在您的代码中,是的,这是可能的。
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
非静态嵌套类(内部类)可以访问封闭类的其他成员,即使它们被声明为私有。静态嵌套类不能访问封闭类的其他成员。
See: Nested Classes
看到:嵌套类
#2
0
If your inner class extends the outer class, then it will have access to the outer class public and protected members. I just tired it and it worked. The construct is a bit odd, because it implies a sort of infinite loop in the class definition, but it seems to do the job.
如果内部类扩展了外部类,那么它将访问外部类public和protected成员。我只是厌倦了它,它起作用了。这个构造有点奇怪,因为它在类定义中暗示了一种无限循环,但它似乎做得很好。
#1
18
In your code, yes, it is possible.
在您的代码中,是的,这是可能的。
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
非静态嵌套类(内部类)可以访问封闭类的其他成员,即使它们被声明为私有。静态嵌套类不能访问封闭类的其他成员。
See: Nested Classes
看到:嵌套类
#2
0
If your inner class extends the outer class, then it will have access to the outer class public and protected members. I just tired it and it worked. The construct is a bit odd, because it implies a sort of infinite loop in the class definition, but it seems to do the job.
如果内部类扩展了外部类,那么它将访问外部类public和protected成员。我只是厌倦了它,它起作用了。这个构造有点奇怪,因为它在类定义中暗示了一种无限循环,但它似乎做得很好。