Please review this code which compiles fine :
class OuterClass {
String a = "A";
String b = "B";
String c = "C";
public static class StaticInnerClass {
}
public String stringConCat() {
return a + b + c;
}
}
this is as i expect as the inner class can access the outer classes attributes. But now when i try the same code but assigning a outer attribute to inner attribute the system complains:
class OuterClass {
String a = "A";
String b = "B";
String c = "C";
public static class StaticInnerClass {
String x = a; //this can not be done, why ?
}
public String stringConCat() {
return a + b + c;
}
}
the error/warning at compile time is: Non-static field a
cannot be referenced from a static context.
is it because in the method stringConCat()
you actually need an instance to call the method (post constructor call) so its allowed ? Whereas, in the second example there is no real instance so it treats it as a static reference ?
I've read I thought inner classes could access the outer class variables/methods? but its still not sinking. Can someone help?