< Prev
Next >



Method-local Inner Class



In the previous article we made a simple/regular version of an inner class in which we defined an inner class inside another class. Now let's see a little complicated version of inner class, which is defined 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 inner class is called a "method-local inner class".

Important point about method-local inner class



How can we create an object of 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 by an example -:
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



Instantiating an object of 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-
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 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 -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Regular Inner Class
Static Nested Class >
Please subscribe for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
JSP & Servlets

Ad2