New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Inner class


In Java, an inner class is also known as nested class. Inner classes are part of nested classes. When a non-static class is defined in nested class then it is known as an inner class. It is defined inside the class or an interface. Inner classes are mostly used to logically group all the classes and the interface in one place, which makes the code more readable and manageable. Inner classes can access members of the outer class including all the private data members and methods.

Syntax:

	
class OuterClass
{  
 //code  
 		class InnerClass
{  
  			//code  
 		}  
}  
	

Types of Nested classes

  1. Non-static nested class
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class
  2. Local inner class

Following are the examples in which inner classes can be defined

1. static inner class with a static method

Example:

	
class outer
{
	static class inner
	{
		public static void add(intx,int y)
		{
			int z = x + y;
			System.out.println("add = " + z);
		}
	}
}
class innerclass_demo1
{
	public static void main(String args[])
	{
		outer.inner.add(15,10);
	}
}
	

inner-class

2. static inner class with non-static method

Example:

	
class outer
{
	static class inner
	{
		public void add(intx,int y)
		{
			int z = x + y;
			System.out.println("add = " + z);
		}
	}
}

class innerclass_demo2
{
	public static void main(String args[])
	{
		outer.innerob = new outer.inner();
		ob.add(12,13);
	}
}
	

static-inner-class

3. non-static inner class with a non-static method

Example:

	
class outer
{
	class inner
	{
		public void add(intx,int y)
		{
			int z = x + y;
			System.out.println("add = " + z);
		}
	}
}

class innerclass_demo3
{
	public static void main(String args[])
	{
		outer ot = new outer();
		outer.inner in = ot.new inner();
		in.add(34,56);
	}
}
	

non-static-inner-class

4. non-static inner class with a static method

Note: it is an illegal combination. Only static variables are allowed and should be final.

Example:

	
class outer
{
	class inner
	{
		/* Illegal combination */
		/*public static void add(intx,int y)
		{
			int z = x + y;
			System.out.println("add = " + z);
		}*/
		public static final int a = 45;
	}
}

class innerclass_demo4
{
	public static void main(String args[])
	{
		outer ot = new outer();
		outer.inner in = ot.new inner();
		System.out.println("Value of a = "+in.a);
	}
}
	

non-static-inner-class

5. Nested inner class in local method

Example:

	
class outer
{
	public void display(intx,int y)
	{
		class inner
		{
			public void add(intx,int y)
			{
				int z = x + y;
				System.out.println("add = " + z);
			}
		}
		
		inner in = new inner();
		in.add(x,y);
	}	
}

class innerclass_demo5
{
	public static void main(String args[])
	{
		outer ob = new outer();
		ob.display(23,56);
	}
}
	

nested-inner-class