Advertisement



< Prev
Next >



Method-local Inner Class in Java





In our previous article we have explained a simple version of an inner class, in which we have defined a class inside another class. Now let us see a little complicated version of an inner class, which is defining a class inside a method of another class. Yes, you've read it right.

We can even define a class inside a method of another class. That's why such version of an inner class is called a method-local inner class.




Important point about method-local inner class:







A simple method-local inner class


Having a method-local inner class imposes a lot of restrictions on how we can instantate its object as compared to instantiating an object of a regular inner class. Let's see this by an example -:

//Java - Example of method local inner class

class OuterC
{
public void  outerMethod()
{
	class InnerC //Inner class cannot have a public/private modifier as it's local to a method
	{
		public void innerMethod() //but it's method can have any modifier because it's declared inside a class.
		{
			System.out.println("Inner method");
		}
	}
	System.out.println("Outer method");
}


public static void main(String... ar)
{
	OuterC ob= new OuterC();
	ob.outerMethod();
}

}


Output is :


Outer method


Program Analysis





Advertisement




Instantiating an object of a method-local inner class and calling its method


The only way to create an object of a method-local inner class is right after the place where its definition ends in the method. Let's understand this by an example.

//Java - Example of method local inner class
 
public class OuterC
{
int b=20;

public void outerMethod()
{
int a=10;
	
	//method-local innner class
	class InnerC 		
	{
		public void innerMethod()
		{
			System.out.println("Inner Method");
			System.out.println("Accessing outerMethod() member variable, a = " + a);
			System.out.println("Accessing outer class member variable, b = " + b);
		}
	}
	InnerC ob = new InnerC();  //method-local inner class can only be instantiated right after its definition ends in the method.
	ob.innerMethod();	   //calling inner class's method
}

public static void main(String... ar)
{
	OuterC ob= new OuterC();
	ob.outerMethod();
}

}


Output is - :


Inner Method
Accessing outerMethod() member variable, a = 10
Accessing outer class member variable, b = 20


Program Analysis




Accessing a method's member variable from within method-local inner class is a feature of JDK 1.8 only, prior to that version of JDK, it gives an error.



Please share this article -





< Prev
Next >
< Regular Inner Class
Static Nested Class >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement