Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java nested inner class access outer class variables

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;
    }
like image 677
TerryProbert Avatar asked Aug 20 '12 17:08

TerryProbert


People also ask

Can inner class access outer class variables?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Can inner class access outer class method?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

Can an inner class be accessed from outside package?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

Can nested class inherit outer class?

Any class can be inherited into another class in C# (including a nested class). The user can inherit a nested class from outer class.


1 Answers

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

like image 145
davidmontoyago Avatar answered Sep 30 '22 05:09

davidmontoyago