Java member inner class



In the previous chapters we have seen the basic overview of the Inner Classes and Its Types. We have also seen the static nested class. In this chapter we are looking first type of Non-Static Nested Class.

Member Inner Classes :

  1. A Member Inner Class is a class whose definition is directly enclosed by another class or interface declaration
  2. Instance of a Member Inner Class can only be created if we have a reference to an instance of outer class.

Invoking Member Inner Class

A. Member Inner Class Invoked from Within Class :

package com.c4learn.nestedclss;

class OuterClass {
  private int serialNo = 10;

  class InnerClass {
      int getValue() {
	return serialNo;
      }
  }

  void displaySerialNo(){
      InnerClass ic = new InnerClass();
      System.out.println("Sr. Number :" + ic.getValue());
  }
}

public class StaticNestedClassExample {

  public static void main(String[] args) {
    OuterClass m1 = new OuterClass();
    m1.displaySerialNo();
  }
}

Output :

Sr. Number :10

Consider the above example, we are calling inner member method from the outer class method itself. i.e –

void displaySerialNo(){
      InnerClass ic = new InnerClass();
      System.out.println("Sr. Number :" + ic.getValue());
  }

thus we need to only create instance of the Inner Class like normal class.

B. Member Inner Class Invoked From Outside Class :

package com.c4learn.nestedclss;

class OuterClass {
   private int serialNo = 10;

   class InnerClass {
      int getValue() {
	return serialNo;
      }
   }
}

public class StaticNestedClassExample {

   public static void main(String[] args) {
     OuterClass m1 = new OuterClass();
     OuterClass.InnerClass ic = m1.new InnerClass();
     System.out.println("Sr. Number :" + ic.getValue());
   }
}

Consider the above example, In this example we are creating the instance of the Inner Class from the Outer class so we need to follow following syntax in order to access method of inner member –

OuterClass outerObj = new OuterClass();
OuterClass.InnerClass innerObj = outerObj.new InnerClass();

Output :

Sr. Number :10