Java的嵌套的内部类访问外部类变量 [英] Java nested inner class access outer class variables
问题描述
是否有可能嵌套的内部类ABAR和的BBar访问主类的变量?例如:
公共类Foo {
公共ABAR ABAR =新ABAR();
公众的BBar BBAR =新的BBar();
公众诠释someCounter = 0; 公共类ABAR {
公众诠释我= 0;
公共无效的someMethod(){
我++;
someCounter ++;
}
} 公共类的BBar {
公共无效anotherMethod(){
bbar.someMethod();
someCounter ++;
}
}
}
//然后使用名为://
美孚myFoo =新的Foo();
myFoo.bbar.anotherMethod();
修改
好像如果我得先试了code我打字会工作;试图得到帮助没有太具体。在code实际上,我遇到的麻烦
失败,因为错误的不能让静态引用非静态字段级
公共类引擎{
公共舞台舞台=新阶段();
// ...
公共类实现渲染{GLSurfaceView.Renderer
// ...
@覆盖
公共无效onDrawFrame(GL10 GL){
stage.alpha ++;
}
} 公共类舞台扩展的MovieClip {
公众持股量的α= 0F;
}
在您的code,是的,这是可能的。
非静态内部类(内部类)可以访问其他成员
封闭类的,即使被声明为private。静止
嵌套类不具有访问封闭的其他成员
类。
块引用>请参阅:嵌套类
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; }
解决方案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
这篇关于Java的嵌套的内部类访问外部类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!