I did read a number of topics discussing inner classes, and i was under the impression that an inner class has access to the variables and methods of the enclosing class. In the following i have an outer class and an inner class, in the test class i create an instance of the outer class and then from that i create an instance of the inner class. However i am not able to access the String variable a through the inner class reference. Help?
public class OuterClass {
String a = "A";
String b = "B";
String c = "C";
class InnerClass {
int x;
}
public static class StaticInnerClass {
int x;
}
public String stringConCat() {
return a + b + c;
}
}
public class TestStatic {
public static void main(String args[]) {
OuterClass.StaticInnerClass staticClass = new OuterClass.StaticInnerClass();
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.a);// error here, why can't i access the string
// variable a here?
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…