10

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;
    }
TerryProbert
  • 1,124
  • 2
  • 10
  • 28

2 Answers2

19

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

davidmontoyago
  • 1,834
  • 14
  • 18
  • 3
    you should include the link to the oracle site if you are going to use direct quotes. http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html – Colin D Aug 20 '12 at 17:59
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.