Programming

Concept of Nested and Inner Classes – Java

Gautam Gautam Donate Nov 27, 2019 · 5 mins read
Concept of Nested and Inner Classes – Java

In Java, you can define a nested class. this is a class that is declared within another class. A nested class does not exist independently of its enclosing class. Thus the scope of nested class is bounded by its outer class.

A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. It is also possible to declare a nested class that is local to a block.

There are two general types of nested classes: those that are preceded by the static modifier and those that are not and the other is the non-static variety. This type of nested class is also called an inner class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that the other non-static members of the outer class do.

Sometimes an inner class is used to provide a set of services that are used only by its enclosing class.

Take a look at an example that uses an inner class to compute various values for its enclosing class:

/*
 *Demonstration of Nested class
 */
 
import java.util.*;

//use an inner class
class outer 
{
	int [] nums;
	
	outer (int[] n)
	{
		nums = n;
	}
	
	void analyze()
	{
		inner inOb = new inner();
		
		System.out.println("Minimum: " + inOb.min());
		System.out.println("Maximum: " + inOb.max());
		System.out.println("Average: " + inOb.avg());
		
	}
	
	//This is an inner class
	
	class inner 
	{
		//Return the minimum value 
		int min()
		{
			int m = nums[0];
			
			for (int i=1; i< nums.length; i++)
				if(nums[i] < m)m = nums[i];
				
			return m;
		}
		
		//Return the maximum value 
		int max()
		{
			int m = nums[0];
			for (int i =1; i < nums.length; i++)
			
				if ( nums[i] > m)m = nums[i];
				
			return m;
			
		}
		
		//Return the average
		int avg ()
		{
			int a = 0;
			for (int i =0; i<nums.length; i++)
			{
				a += nums[i];
			}
			return a/nums.length; 
			
		}
	}
}

class NestedClassDemo
{
	public static void main (String args[])
	{
		
		int [] x = { 3, 2, 1, 5, 6, 9, 7, 8	};
		outer outOb = new outer (x);
		
		outOb.analyze();
	}
}

The above program generates the following output - 

Minimum: 1
Maximum: 9
Average: 5

In this example, the inner class Inner computes various values from the array nums, which is a member of Outer. Since an inner class has access to the members of its enclosing class, so it is perfectly acceptable for Inner to access the nums array directly.

The opposite, however, is not true. for example, it would not be possible for analyze() to invoke the min() method directly, without creating an Inner object.

since it is possible to nest a class within a block scope. Doing so simply creates a localized class that is not known outside its block. Take a look at the following program -

/*
 *Use BitOut as a local class
 */
 
 import java.util.*;
 
 class LocalClassDemo
 {
 	public static void main (String args[])
 	{
 		//An inner class version of BitOut 
 		class BitOut 
 		{
 			//A local class nested within method
 			int numBits;
 			
 			BitOut (int n)
 			{
 				if (n < 1) n = 1;
 				if(n > 64) n = 64;
 				numBits = n;
 			}
 			
 			void show (long val)
 			{
 				long mask = 1;
 				//left-shift a 1 into the proper position
 				mask <<=numBits-1;
 				int spacer = 8 - (numBits % 8);
 				for (; mask !=0; mask >>>=1)
 				{
 					if ((val & mask) != 0) 
 						System.out.println("1");
 					else
 					{
 						System.out.println(" ");
 						spacer = 0;	
 					}
 				}
 				System.out.println();
 			}
 		}
 		
 		for (byte b =0; b < 10; b++ )
 		{
 			BitOut byteval = new BitOut (8);
 			System.out.print(b + " in binary: ");
 			byteval.show(b);
 		}
 	}
 }

Output - 

0 in binary:  00000000
1 in binary:  00000001
2 in binary:  00000010
3 in binary:  00000011
4 in binary:  00000100
5 in binary:  00000101
6 in binary:  00000110
7 in binary:  00000111
8 in binary:  00001000
9 in binary:  00001001

In this example, the BitOut class is not known outside of main(), and any attempt to access it by any method other than main() will result an error.

You can create an inner class that does not have a name. This is called an anonymous inner class. An object of an anonymous inner class is instantiated when the class is declared, using new. 


Tags

Join Newsletter
Get the latest news right in your inbox. We never spam!
Gautam
Written by Gautam Sharma Profile
Developer, Writer, Emotional, loves to help, blogger

Connect with Gautam