Java nested inner class access outer class variables

天涯浪子 提交于 2019-12-23 07:31:32

问题


Is it possible for the nested inner classes ABar and BBar to access main class's variables? For example:

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;
    }

回答1:


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:


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.



来源:https://stackoverflow.com/questions/12042573/java-nested-inner-class-access-outer-class-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!