Local Inner classes in java

Previous
Next

Local inner classes:

  • Defining a class inside the block or method or constructor.
  • It is working like a local variable in Java application.
  • Access modifiers cannot be applied to the local inner classes.
  • Local inner class cannot be static.
  • It is allowed to define more than one class with the same name in two different blocks of same Outer class. Hence we can achieve ‘Name control’ benefit of java classes.
  • Compiler generates the class file for same class which is defined more than one time by using constant integer values.

Class files generation of location inner classes as follows:

class Outer 
{
	static
	{
		class LocalInner
		{
			//Outer$1LocalInner.class
		}
	}
	Outer
	{
		class LocalInner
		{
			//Outer$2LocalInner.class
		}
	}
}

Scope of local inner class is always restricted to that block where it has defined:

class Outer 
{
	static
	{
		class LocalInner
		{
			void check()
			{
				System.out.println("Class inside block...");
			}
		}
		new LocalInner().check();
	}
	Outer()
	{
		class LocalInner
		{
			void check()
			{
				System.out.println("Class inside constructor...");
			}
		}
		new LocalInner().check();
	}
	public static void main(String args[ ])
	{
		new Outer();
	}
}

More than one level of local inner classes(as shown below) creates complex user defined data types.

class Outer 
{
	Outer()
	{
		class LocalInner
		{
			void check()
			{
				System.out.println("Class inside constructor...");
				class InnerInner
				{
					void check()
					{
						System.out.println("Class inside method....");
					}
				}
				new InnerInner().check();
			}
		}
		new LocalInner().check();
	}
	public static void main(String args[ ])
	{
		new Outer();
	}
}
Previous
Next

Add Comment

Courses Enquiry Form