A non-static class that is created inside a class but outside a method is called member inner class.
class Outer{ //code class Inner{ //code } }
In this example, we are creating msg() method in member inner class that is accessing the private data member of outer class.
class TestMemberOuter1{ private int data=30; class Inner{ void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ TestMemberOuter1 obj=new TestMemberOuter1(); TestMemberOuter1.Inner in=obj.new Inner(); in.msg(); } }
The java compiler creates two class files in case of inner class. The class file name of inner class is "Outer$Inner". If you want to instantiate inner class, you must have to create the instance of outer class. In such case, instance of inner class is created inside the instance of outer class.
The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
import java.io.PrintStream; class Outer$Inner { final Outer this$0; Outer$Inner() { super(); this$0 = Outer.this; } void msg() { System.out.println((new StringBuilder()).append("data is ") .append(Outer.access$000(Outer.this)).toString()); } }