有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

嵌套的内部类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();

编辑

看来如果我先试试的话,我输入的代码会有用的;试图在不太具体的情况下寻求帮助。我实际上遇到麻烦的代码

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

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. # 1 楼答案

    在你的代码中,是的,这是可能的

    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.

    见:Nested Classes

  2. # 2 楼答案

    如果您的内部类扩展了外部类,那么它将有权访问外部类的公共成员和受保护成员。我只是厌倦了它,它起了作用。这个构造有点奇怪,因为它在类定义中暗示了一种无限循环,但它似乎完成了这项工作