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;
}
Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.
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.
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.
Any class can be inherited into another class in C# (including a nested class). The user can inherit a nested class from outer class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With