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 inner class can access the outer class methods and properties through its own methods. Look at the following code:
class OuterClass {
String a = "A";
String b = "B";
String c = "C";
class InnerClass{
int x;
public String getA(){
return a; // access the variable a from outer class
}
}
public static class StaticInnerClass{
int x;
}
public String stringConCat(){
return a + b + c;
}
}
public class Test{
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.getA()); // This will print "A"
}
}
System.out.println(inner.a);
You are attempting to read a
as if it is a property of you inner class, but it's not. You should define a method that will read the desired property of the outer class. So in your inner class, you should have:
public String getA(){
return a;
}
System.out.println(inner.getA());
This should work.
inner
is an instance of OuterClass.InnerClass
which doesn't defines a
so it wont be able to access it anyways.
To understand it in the simplest manner... look at the block in which a
is created and the block in which OuterClass.InnerClass
is defined.
public class OuterClass { // a is defined in this block
String a = "A";
class InnerClass{ // InnerClass starts here and an instance will access what is defined now
int x;
}
}
An Non-static inner class
has an implicit reference to the OuterClass
.....
Try it out like this.....
class OuterClass {
String a = "A";
String b = "B";
String c = "C";
class InnerClass {
String x = a; // Directly uses the instance variable a from Outer class
}
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.x);
}
}
It seems you're confusing scope and access. References can access only the attributes and methods of the object to which they refer. So your inner.a
can't work.
On the other hand, outer class variables are within the scope of methods in a respective inner class. So you can do what you want by defining a read accessor.
public class OuterClass {
String a = "A";
String b = "B";
String c = "C";
class InnerClass{
int x;
String getA() {
return a;
}
}
}
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.getA()); //error should be gone now.
}
}