dsa

Java Nested & Inner Class

In this tutorial, you will learn about the nested class in Java and its types with the help of examples.

What is Nested Class ?

In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.

Types of Nested Class

  1. static nested class : Nested classes that are declared static are called static nested classes.
  2. Non-static nested class (inner class) A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as inner class.Since the inner class exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.

Syntax :


class OuterClass
{
	...
    	class NestedClass
    	{
        	...
    	}
}

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.

Example :

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

Output :

Data is 30

Inner Classes (Non-static Nested Classes)

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.


class Outer 
{
   	int num;
   
   	// inner class
   	private class Inner_Demo 
	{
      		public void print() 
		{
         		System.out.println("This is an inner class");
      		}
   	}
   
   	// Accessing he inner class from the method within
   	void display_Inner() 
	{
      		Inner_Demo inner = new Inner_Demo();
      		inner.print();
   	}
}
   
public class My_class 
{

   	public static void main(String args[]) 
	{
      		// Instantiating the outer class 
      		Outer_Demo outer = new Outer_Demo();
      
      		// Accessing the display_Inner() method.
      		outer.display_Inner();
   	}
}  

Output :

This is an inner class