10

嵌套的内部类 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;
    }
4

2 回答 2

19

在您的代码中,是的,这是可能的。

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

请参阅:嵌套类

于 2012-08-20T17:57:31.980 回答
0

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

于 2013-12-20T21:54:55.310 回答