Java Inner Classes

Java inner class or nested class is a class which is declared inside the class or interface

1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Type

Description

Member Inner Class

A class created within class and outside method.

class TestMemberOuter1
{  

private int data=30;
        class Inner{  
         void msg(){System.out.println("data is "+data);}  
        }  


public static void main(String args[])
{  
         TestMemberOuter1 obj=new TestMemberOuter1();  
         TestMemberOuter1.Inner in=obj.new Inner();  
         in.msg();  
     }  
 }  

Anonymous Inner Class

A class created for implementing interface or extending class. Its name is decided by the java compiler.

      abstract class Person{  
         abstract void eat();  
       }  

       class TestAnonymousInner{  
        public static void main(String args[]){  
         Person p=new Person(){  
         void eat(){System.out.println("nice fruits");}  
         };  
         p.eat();  
    }  
   }  

Local Inner Class

A class created within method.

public class localInner1{  

        private int data=30;//instance variable  
        void display(){  

         class Local{  
          void msg(){
        System.out.println(data);
        }  
         }  

         Local l=new Local();  
         l.msg();  
        }  

      public static void main(String args[]){  
       localInner1 obj=new localInner1();  
       obj.display();  
      }  
     }  

Static Nested Class

A static class created within class.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.

class TestOuter1{  
 static int data=30;  
 static class Inner{  
   void msg(){
   System.out.println("data is "+data);
  }  
}  
  public static void main(String args[]){  
  TestOuter1.Inner obj=new TestOuter1.Inner();  
  obj.msg();  
  }  
}  

Nested Interface

An interface created within class or interface.

  • Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static implicitely.