Nested Class in Java

Nested classes can be precisely defined as classes within a class, a member of an other class. Let’s discuss below with an example for clear understanding,

class OuterClass
 {
     int abc;       //Field as a member
     void methodOfOuterClass() 
     {     
       //method of outer class 
     } 
     class NestedClass 
     {     
        //Nested Class 
     }
 }

Nested classes are classified into two types:

  1. Static Nested Classes

2. Non-Static Nested Classes or Inner Classes

Let’s discuss each topic in detail below:

Static Nested Classes

If we declare the nested classes as static then the classes are known as static Nested Classes.

class OuterClass
{
    int staticNestedClass;       //Field         as a member
 
    void methodOfOuterClass()
    {
        //method of outer class
    }
 
    static class NestedClass
    {
    	//Nested class as a member which is declared as static
    }
}

Non-Static Nested Classes

Classes which are declared Nested and as non-static or nested classes and can be accessed only though instantiating the outer class is called non-static nested classes.

They are 3 types of Inner Classes in java.
1. Member Inner Classes
2. Local Inner Classes
3. Anonymous Inner classes

Member Inner Classes

Member Inner Classes are non-static nested classes which are to be declared as non-static members of outer class.

Let’s us now discuss important points about member inner classes.

  • non-static members should be present in Member inner classes.
  • Member inner classes does not allow static member inside it.
  • Member inner class contain any number of IIB’s but should not contain SIB’s.
  • Static and non-static members of outer class can be accessed inside member inner class.
class OuterClass
 {
     //Member Inner Class : Class As a Non-Static Member
     class InnerClass
     {
         int i;    //can contain non-  static field
     static int j = 10;    
//It gives compile time error     
//Should not contain static field   
  
void methodOne()     
{         
//can have non-static method     
}     
static void methodTwo()     
{         
//Compile time error         
//should not contain static method     
} 
}
}

Anonymous Inner Classes

The name itself suggests that the class is itself without a name. an inner class or non-static nested class without a name is Anonymous Inner Class.

Below is an example for clear understanding:

class SuperClass
 {
     void methodOne()
     {
         System.out.println("From SuperClass");
     }
  
     void methodTwo()
     {
         System.out.println("From SuperClass");
     }
 }

Leave a Reply