Nested classes in Java

Java nested class and java inner class is the one of most confusing and important topics. Firstly, I want to tell Java nested class and java inner class are not the same concept, most programmers misunderstood them. In Java, inner classes are part of nested classes. Most programmers know about nested class in java, but the problem starts when the interviewer asks what is the use of nested classes or the use of inner class in java and java inner class example? In this post, we will discuss the types of inner classes in java like the java anonymous class, java static inner class, local inner class in java.

Here is the table content of the article we will cover this topic.
1. What is the nested class in Java?
2. Important points about the nested class?
3. Types of nested classes?
4. static nested class in java?

5. Access to Static nested class?
6. Creating an object of static nested class?
7. Non-static nested class in java?
8. Inner class in java?
9. How to instantiate the Member Inner class(java member class) in java?
10. How to access members of the Inner class from the Outer class?
11. How to access members of the Outer class from the Inner class(java member class)?
12. Accessing the static members of Outer Class?
13. What is a private inner class?
14. What is the method local inner class?
15. How to instantiate method local inner class in java?
16. Access modifier with method local inner class?
17. Access members in method local Inner class?
18. What is an anonymous class in java?
19. How to create an anonymous class in java?
20. Advantages of nested class in Java

What is the nested class in Java?

We can define a class inside another class, that class is known as a java nested class. The class that contains the other class is known as the outer class and the contained class is known as inner class. The concept of nested class was introduced to achieve logical grouping of classes and provide more encapsulation. We will learn it in the next section i.e. Why do we need the nested class?

OuterClass
{
    // Body of OuterClass
   InnerClass
   {
        /// Body of InnerClass
   }
}

The nested classes work together and provide better readability for the program.

We have two categories of nested classes, ie. Static nested class and non-static nested class(inner classes). We don’t use static keyword with Inner classes. We will discuss it in detail.  

class OuterClass 
{
     // Body of OuterClass
    static class StaticNestedClass 
    {
        // Body of StaticNestedClass 
    }
    class InnerClass 
    {
        // Body of OuterClass
    }
}

A nested class can be static or non-static.

Important points about nested class

Nested class scope

Scope of the nested class binds with its enclosing class. The InnerClass doesn’t exist without the OuterClass and it totally depends on OuterClass. You can’t access InnerClass without using OuterClass.

Access class members of the inner class

InnerClass can access the members of the OuterClass Wheather they are private or not. A static nested class can access only the static member of OuterClass. But the OuterClass can’t access any member of InnerClass.

Access modifier

We can use any access modifier with a nested class. As we know we can’t use a private or protected access modifier with a normal class. But we can use privatepublicprotected, or default keywords with nested classes. 

Types of nested classes

There are two types of nested classes in java.
1. Static nested classes in java
2. Non-static nested class in java(Inner classes in java)
i). Nested inner class in java or member inner class in java
ii). Local inner class in java or method local inner class in java
iii). Anonymous inner class in java

Nested classes in Java

What is the static nested class in java?

To declare a static nested class we used a static keyword with a nested class. We can’t declare an outer class as a static class.

Important points about it?

  • In Java, the static class can’t access non-static variables and methods.
  • It can be accessed by an outer class name.
  • It can access the static variables and static methods of the outer class including private.
class OuterClassName
{
   // variables and method of outer class
   static class className
   {
	// variables and method of static class
   }
}
class College
{
	// variables and method of College class
	static class Student
        {
		// variables and method of Student class
        }
}

Access to Static nested class

You can’t directly access the nested static class. It can access by the use of an outer class.

OuterClassName.StaticNestedClassName;
College.Student;

Creating an object of static nested class

You can create an object of the static nested class by use of an outer class.

OuterClassName.StaticNestedClassName objectName = new outerClassName.StaticNestedClassName();
College.Student object = new College.Student();

Let’s take an example of a static nested class. Here College is the Outer class and Student is a static nested class. We declared some static and non-static variables and methods. Some of them are accessible and the rest are not able to access.

class College
{
   // Non static variable
   int nonStaticVariableOfCollege = 5;

   // static variable
   static int staticVariableOfCollege = 10;

   // private and static variable
   private static int privateAndStaticVariableOfCollege = 15;

   // Non- static method
   void nonStaticShowMethod()
   {
      System.out.println("This is Non static method of college class");
   }

   // static method
   static void staticShowMethod()
   {
     System.out.println("This is static method of college class");
   }

   //private and static method
   private static void privateStaticShowMethod()
   {
     System.out.println("This is private and static method of college class");
   }

   // static nested class
   static class Student
  {
    // Non static method of Student class
    void display()
   {
       // You can't access the non static variables of College class.
       //System.out.println("You can't access the non static variable      
        ="+nonStaticVariableOfCollege);

       // You can access the static variables of College class.
       System.out.println("You can access the static variable ="+staticVariableOfCollege);

       // You can access the private static variables of College class.
       System.out.println("You can access the priavte static variable 
       "+privateAndStaticVariableOfCollege);

        // You can access the static method of College class.
       staticShowMethod();

       // You can access the private static method of College class.
       privateStaticShowMethod();

       // You can't access the non static method of College class.
       // nonStaticShowMethod();
}

// Non static method of Student class
static void displayData()
{
System.out.println("This is static method of Student class");
}
              }
}


public class MainClass
{
    public static void main(String[] args)
    {
          // accessing a static method of Student class
          College.Student.displayData();

         // Accessing of non-static method we must create object of Student
        College.Student object = new College.Student();
        // Accessing of non static method
        object.display();
      }
}

Output:This is static method of Student class
You can access the static variable =10
You can access the priavte static variable 15
This is static method of college class
This is private and static method of college class

As you see in the above example, To access the static method we are using the class name, and the non-static can be accessed by an object.

Non-static nested class in java

Inner class in java

The nested inner class is the simplest form of an inner class in Java. It is also known as member inner class because we can declare the class as a member of another class. The member inner class is always outside the method and inside the class. A member inner class can be declared with any access modifier like private, protected, public, and default.
It is the only way when we can create a class as private and protected. We will see how we can create a private class in java.

java member class

Let’s take another example

public class OuterClass 
{
    // Method of outer class
	void methodOfOuter()
	{
		System.out.println("Outer class");
	}
    
	// Creating member inner class 
	class InnerClass 
	{
        // Method of member inner class
	    public void methodOfInner() 
        {
			System.out.println("Inner class");
		}
	}
	public static void main(String[] args) 
       { 
		//Body of the main method
       }
}

How to instantiate the Member Inner class(java member class) in java?

We can’t create an object or instance of a member inner class directly. The object/instance of a member inner class totally depends on the object of the outer class. Unlike a normal class, the nested class has a different way to create an object or instance.

java member class

To create an object of a member inner class we need to create an object of the Outer class first. The scope of member inner class always enclose in the Outer class.

OuterClass objOfOuter = new OuterClass();
InnerClass objOfInner = objOfOuter.new InnerClass();
public class OuterClass 
{
    // Method of outer class
	void methodOfOuter()
	{
		System.out.println("Outer class");
	}
    
	// Creating member inner class 
	class InnerClass
	{
        // Method of member inner class
	    public void methodOfInner() 
        {
			System.out.println("Inner class");
		}
	}
	public static void main(String[] args) 
    { 
		OuterClass objOfOuter = new OuterClass();
		InnerClass objOfInner = objOfOuter.new InnerClass();
		objOfOuter.methodOfOuter();
		objOfInner.methodOfInner();
    }
}

Output: Outer class
Inner class

How to access members of the Inner class from the Outer class?

We can access the member of the Inner class in the Outer class by the object of the Inner class. We can directly access the member of the Inner class in a static method as well as in the non-static method(Instance method).

Scenario 1: In the static method can access the member of the Inner class only when we create an object of the Inner class. To create an Inner class we have to use the object of the Outer class.

Scenario 2: But in the instance method(non-static method) we can directly create the object of the Inner class. Let’s take an example and see how we can access it.

public class OuterClass 
{
    // Creating member inner class 
	class InnerClass
	{
		int a = 5;
        // Method of member inner class
	    public void methodOfInner() 
        {
			System.out.println("Inner class");
		}
	}
        public static void main(String[] args) 
        { 
		OuterClass objOfOuter = new OuterClass();
		InnerClass objOfInner = objOfOuter.new InnerClass();
		System.out.println("Value of a = " +objOfInner.a);
		objOfInner.methodOfInner();
		
		objOfOuter.showData();
        }
	
	void showData()
	{
		InnerClass objOfInner = new InnerClass();
		System.out.println("Show data method and value of a : "+ objOfInner.a);
		objOfInner.methodOfInner();
	}
}

Output: Value of a = 5
Inner class
Show data method and value of a : 5
Inner class

java member class

How to access members of the Outer class from the Inner class(java member class)?

Access each and every member of the Outer class from the Inner class. Even if they are private or not. This is the only way to access the private member of a class.

public class OuterClass 
{
    private int a = 1; // private variable
    protected int b = 2; // protected variable
    public int c = 3; // public variable
    int d = 4; // default variable
	
    // Creating member inner class 
	class InnerClass
	{
        // Method of member inner class
	    public void methodOfInner() 
        {
			System.out.println("Accessing private variable : "+ a);
			System.out.println("Accessing protected variable : "+ b);
			System.out.println("Accessing public variable : "+ c);
			System.out.println("Accessing default variable : "+ d);
		}
	}
        public static void main(String[] args) 
        { 
		OuterClass objOfOuter = new OuterClass();
		InnerClass objOfInner = objOfOuter.new InnerClass();
		
		objOfInner.methodOfInner();
		
        }
}

Output: Accessing private variable : 1
Accessing protected variable : 2
Accessing public variable : 3
Accessing default variable : 4

Accessing the static members of Outer Class

We can access the static member of the Outer class. Although we can’t use static keyword in the Inner class, we can access the static member of the outer class. We don’t need to create an object of Outer class to access the static members.

public class OuterClass 
{
	static int a = 5;
	static void shwoData()
	{
		System.out.println("Static method Outer class");
	}
	
    // Creating member inner class 
	class InnerClass
	{
	    public void methodOfInner() 
        {
			System.out.println("Static variable of Outer class a :"+ a);
			shwoData();
		}
	}
	public static void main(String[] args) 
    { 
		OuterClass objOfOuter = new OuterClass();
		InnerClass objOfInner = objOfOuter.new InnerClass();
		objOfInner.methodOfInner();
    }
}

Output: Static variable of Outer class a :5
Static method Outer class

What is a private inner class?

We know a class can’t be associated with the access modifier private, but if we have the class as a member of other classes, then the inner class can be made private.

class OuterClassName
{
	// variables and methods of Outer Class
	private class InnerClassName
        {
		// variables and methods of Inner class
        }
}
class Data 
{  
    // variable of Data class
    int variableOfData = 5;
	
    // inner nested class 
    private class Record 
    { 
    	// Non static method of Student class
        void display() 
        { 
        	// You can access the variables of Data class.
            System.out.println("You can access the variable ="+variableOfData);
        } 
    } 
    
    // Method of Data class
    void methodOfData()
    {
    	Record record = new Record();
    	record.display();
    }
} 
  
public class MainClass 
{ 
    public static void main(String[] args) 
    { 	
    	Data data = new Data();
    	data.methodOfData();
    } 
}

Output: You can access the variable =5

Internal working by the compiler

The compiler internally works differently in the case of inner classes. The compiler creates two class files in the case of an inner class. One class file for Outer class and another for Inner class. The class file name of the inner class is “Outer$Inner”. If you want to create an object of the Inner class, you must have to create an object of the Outer class.

What is the method local inner class?

A class declares inside a block or method known as a local inner class or method local in class. A method local inner class can’t be declared as a member of the class. The scope of method local inner class lies within the outer class, just as a local variable. It doesn’t accessible outside the block. Generally, programmers declare the class in a method that’s why it is called method local inner class. You can declare a class inside of for loop, or an if clause also.

local inner class in java
public class OuterClass 
{
	void outerClassMethod()
	{
		// Creating method inner class 
		class InnerClass
		{
			public void innerClassMethod()
			{
				System.out.println("Method of inner class");
			}
		}
	}
	
        public static void main(String[] args) 
        {
        	//Body of main method
        }
}

Important points local inner class in Java

1. A local inner class or method local inner class can’t be declared as a member of the outer class. The method local inner class belongs to the block/method in which they are defined.
2. The method local inner class can access the fields of the Outer class.
3. We can’t use any access modifiers with the method local inner class. It means the method local inner class can’t use private, public, or protected access modifiers with it.
4. We can use use the abstract keyword and final keyword with the method local inner class.
5. The method local inner class should be instantiated within a block/method where it is created.  You can’t instantiate it from outside the block/method.
6. A method local inner class in Java can access only the final local variable of the enclosing block. But from JDK 8, it is possible to access the non-final local variable of enclosing block in the local inner class.
7. Method local inner class can extend an abstract class or can also implement an interface.

How to instantiate method local inner class in java?

To create an object of method local inner class we need to choose the right place. We can create an object only after the place where its definition ends in the method. Unlike the member inner class, We don’t need the object of the outer class to create an object of method local inner class.

public class Outerclass
{
   void outerClassMethod() 
   {
      // method-local inner class
      class InnerClass 
      {
         public void innerClassMethod() 
         {
            System.out.println("Method of inner class");       
         }   
      } // end of inner class
        
      // Accessing the inner class
      InnerClass obj = new InnerClass();
      obj.innerClassMethod();
   }
    
   public static void main(String args[]) {
      Outerclass outer = new Outerclass();
      outer.outerClassMethod();           
   }
}

Output: Method of inner class

Access modifier with method local inner class

A method local inner class can’t declare with the private, protected, and public access modifiers. It can be only a default access modifier and we already know if we are not defining any access modifier then it is considered the default. A method local inner class is not associated with any object. If we will try to use any modifier with the class name the compiler will show the compilation error. We can only use the abstract keyword or final keyword with it.

public class Outerclass
{
   void outerClassMethod() 
   {
      // method-local inner class
      public class InnerClass 
      {
         public void innerClassMethod() 
         {
            System.out.println("Method of inner class");       
         }   
      } // end of inner class
        
      // Accessing the inner class
      InnerClass obj = new InnerClass();
      obj.innerClassMethod();
   }
    
   public static void main(String args[]) {
      Outerclass outer = new Outerclass();
      outer.outerClassMethod();           
   }
}

Output: Compilation error

Access members in method local Inner class

As we know a local inner class can be defined in the method. Like a member inner class, the method local inner class can access all the variables of the outer class. Even they are private members or not.

public class Outerclass
{
   int a = 5;
   final int b = 10;
   void outerClassMethod() 
   {
	   int c = 15;
	   final int d = 20;
      // method-local inner class
      class InnerClass 
      {
         public void innerClassMethod() 
         {
            System.out.println("a :"+a);       
            System.out.println("b :"+b);
            System.out.println("c :"+c);
            System.out.println("d :"+d);
         }   
      } // end of inner class
        
      // Accessing the inner class
      InnerClass obj = new InnerClass();
      obj.innerClassMethod();
   }
    
   public static void main(String args[]) {
      Outerclass outer = new Outerclass();
      outer.outerClassMethod();           
   }
}

Output: a :5
b :10
c :15
d :20

What is an anonymous class in java?

An inner class that is declared without a name is known as an anonymous class in java. The anonymous class is also known as an anonymous inner class. Because the anonymous class is possible only with the inner class. We can declare an anonymous class(a class without a name) only inside another class. If you’re not familiar with inner class in java then you should read them first. We will see the syntax of an anonymous class.

anonymous class in java

As you can see in the above syntax, we are declaring the anonymous class as well as creating an object of the anonymous class.  An anonymous class can be providing a body to interface, abstract/concrete class. The anonymous class is used when you want to use any class only once. An anonymous class can declare by the use of a new keyword.

How to create an anonymous class in java?

There are two ways to create an anonymous class in java.

1. Create an anonymous class by using of class
2. Create an anonymous class by using of Interface

1. Create an anonymous class by using of class

You can create an anonymous class by use of another class. It may be an abstract or concrete class.

By use of abstract class

You can create an object of an abstract class. You can use an anonymous class. In the anonymous class, you must have to define the body of the method while creating the object of that class.

abstract class Student
 {  
	abstract void record();  
 } 
class AnonymousInnerExample
 {  
	public static void main(String args[])
	{  
		Student obj = new Student()
		{  
		   void record()
		   {
			System.out.println("This method is defined in anonymous class");
		   }  
 };  
  obj.record();  
 }  
}  

Output: This method is defined in anonymous class

By use of concrete class

If you want to create an object of a concrete class as in an anonymous class. Then you must have to override the body of the method while creating the object of that class.

class Student
{  
     void record()
     { }
} 
class AnonymousInnerExample
{  
	public static void main(String args[])
	{  
		Student obj = new Student()
		{  
			void record()
			{
			   System.out.println("This method is defined in concrete class");
			}  
};  
  obj.record();  
 }  
} 

Output: This method is defined in anonymous class

2. Create an anonymous class by using of Interface

You can create an anonymous class by use of Interface. If you want to create an object of an Interface. You can use an anonymous class. In the anonymous class, you must have to define the body of the method while creating the object of that Interface.

interface Student
{  
    void record();
}
class AnonymousInnerExample
{  
	public static void main(String args[])
	{  
		Student obj = new Student()
		{  
		    public void record()
        	    {
			System.out.println("This method is defined in anonymous class");
		    }  
 };  
 obj.record();  
 }  
} 

Output: This method is defined in anonymous class

Important point:

  • Anonymous class has no name
  • It can be instantiated only once
  • It is usually declared inside a method or a code block, curly braces ending with a semicolon.
  • It is accessible only at the point where it is defined.
  • It does not have a constructor simply because it does not have a name
  • It cannot be static

Advantages of nested class in Java

1. By use of nested classes, the inner class can access all variables and methods of outer
class. It can access private variables or methods.
2. It provides good maintains and readability of code.
3. It requires less code that lead to code optimization.
4. The concept of nested classes to increase the use of encapsulation.

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.