How nested class works ?



How to : Nested Class

Consider the following – When we compile the above program, it will be compiled into two classes : Outer.class and Outer$Inner.class

public class Outer {
    class Inner {
    }
}

If we consider the anonymous inner classes inside the Outer class then –

interface InnerInterface {
}

public class Outer {
    InnerInterface w1 = new InnerInterface() {
    
    };
}

Above class will be compiled into two classes : Outer.class and Outer$1.class

Sample Example :

Consider the following class –

class Outer {
     private int value = 9;
     class Inner {
         int getValue() {
            return value;
         }
    }
}

Above program after compilation will be converted to –

class Outer {
     private int value = 9;
     Outer() {
	 }
     
	 // added by the compiler
     static int access$0(Outer o1) {
         return o1.value;
     }
}

class Outer$Inner {
     final Outer this$0;
     Outer$Inner(Outer o1) {
         super();
         this$0 = o1;
     }
     int getValue() {
        // modified by the compiler
        return Outer.access$0(this$0);
     }
}