Java嵌套内部类访问外部类变量

Ter*_*ert 9 java android opengl-es

嵌套的内部类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();
Run Code Online (Sandbox Code Playgroud)

编辑

似乎我输入的代码如果我先试过它就会起作用; 我试图在没有太具体的情况下获得帮助.代码我实际上遇到了麻烦

由于错误'无法对非静态字段进行静态引用'而失败

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;
    }
Run Code Online (Sandbox Code Playgroud)

dav*_*ago 18

在你的代码中,是的,它是可能的.

非静态嵌套类(内部类)可以访问封闭类的其他成员,即使它们被声明为私有.静态嵌套类无权访问封闭类的其他成员.

请参阅:嵌套类

  • 如果要使用直接引号,则应包含指向oracle站点的链接.http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html (3认同)