How to instantiate member inner class in Java?


A class that is declared inside a class but outside a method is known as member inner class.

We can instantiate a member Inner class in two ways

  • Invoked within the class
  • Invoked outside the class

Rules for Inner Class

  • The outer class (the class containing the inner class) can instantiate as many numbers of inner class objects as it wishes, inside its code.
  • If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  • No inner class objects are automatically instantiated with an outer class object.
  • If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class.
  • The outer class can call even the private methods of the inner class.

Member Inner Class that is invoked inside a class

In the below example, we are invoking the method of member inner class from the display() method of OuterClass.

Example

Live Demo

public class OuterClass {
   private int value = 20;
      class InnerClass {
         void show() {
            System.out.println("Value is: " + value);
      }
   }
   void display() {
      InnerClass ic = new InnerClass();
      ic.show();
   }
   public static void main(String args[]){
      OuterClass oc = new OuterClass();
      oc.display();
   }
}
Value is: 20


Member Inner Class that is invoked outside a class

In the below example, we are invoking the show() method of InnerClass from outside the OuterClass i.e. Test class.

Example

Live Demo

class OuterClass {
   private int value = 20;
      class InnerClass {
         void show() {
            System.out.println("Value is: "+ value);
      }
   }
}

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

Output

Value is: 20
raja
Published on 14-Jun-2019 17:08:19
Advertisements