Inner Classes

Reading Time: 1 minute

Hi,

This post is about Inner Classes, which could be useful when you are learning Lambda Expressions and Functional Programming in Java 8.

Member Inner Class

They can access private variables of outer class.

public class MemberInnerClass {
 private int outer = 5;

 class Inner {
   private int inner = 10;

   public void print() {
     System.out.println(outer);
     System.out.println(inner);
   }
 }

 public static void main(String[] args) {
    new MemberInnerClass().new Inner().print();
 }
}

Output: 5 
        10

Local Inner Class

They are defined in a method.

public class Outer {
 private int i = 5;

 public void print() {
   class Inner {
     private int i = 10;

     public void print() {
       System.out.print(i);
     }
   }
   Inner in = new Inner();
   in.print();
 }

 public static void main(String[] args) {
 new Outer().print();
 }
}

Output: 10

Anonymous Inner Class

They are the base for Lambda Expressions in Java 8. Most of the tutorials I have seen first explain the relation between Anonymous Inner Classes and Lambdas. They enable you to declare and instantiate a class at the same time. They must extend a class or implement an interface. Use them if you need to use a local class only once (1).

public class AnonymousInnerClassImplementsInterface {
 private int i = 5;

 interface Interface {
   void print();
 }

  public void print() {
    class MustImplement implements Interface {
    private int i = 10;

    public void print() {
      System.out.print(i);
    }
  }
  MustImplement imp = new MustImplement();
  imp.print();
 }

 public static void main(String[] args) {
   AnonymousInnerClassImplementsInterface aic= new AnonymousInnerClassImplementsInterface();
   aic.print();
 }
}

Static Nested Class

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference (2).

public class StaticNestedClass {
 
 static class StaticClass {
   private int inner = 10;
 }

 public static void main(String[] args) {
     System.out.println(new StaticClass().inner);
 } 
} 
Output: 10