Member inner class

A class that is declared inside a class but outside a method is known as member inner class.
Invocation of Member Inner class
  1. From within the class
  2. From outside the class
Example of member inner class that is invoked inside a class
In this example, we are invoking the method of member inner class from the display method of Outer class.
class Outer{
   private int value = 70;
   class Inner{
      void show(){
          System.out.println("value is "+value );
      }
    }
 
   void display(){
     Inner in = new Inner();
     in.show();
   }
  public static void main(String args[]){
    Outer obj = new Outer();
    obj.display();
  }
}
output:
Member inner class

See in the directory there are the two following class files after compiling.
Outer.class
Outer$Inner.class

Internal code generated by the compiler for member inner 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 show()
    {
        System.out.println((new StringBuilder()).append("value is ")
                    .append(Outer.access$000(Outer.this)).toString());
    }
 }


Example of member inner class that is invoked outside a class

In this example, we are invoking the show() method of Inner class from outside the outer class i.e. Test class.

//Program of member inner class that is invoked outside a class
class Outer{
  private int value = 70;
  class Inner{
   void show(){System.out.println("value is "+value);}
  }
}

class Test{
  public static void main(String args[]){
    Outer obj = new Outer();
    Outer.Inner in = obj.new Inner();
    in.show();
  }
}

output:
Member inner class in java

Rules for Inner Classes:
Following properties can be noted about Inner classes:
<OuterClassName> outerObj = new <OuterClassName>(arguments);
outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);
<OuterClassName>.this.<variableName>



<<Previous <<   || Index ||   >>Next >>


Labels: