As you can perceive from the heading itself, a
method-local-inner class is defined within a method's body. And, can be used
within the same method it was defined in. For that you have to create an
instance of it below the inner class definition.
Because a method-local-inner-class is defined within
a method, it can only be instantiated within the method. No other code outside
the method can instantiate this type of inner class.
Important point to notice is like regular inner
class objects, the method-local inner class object shares a special
relationship with the enclosing class object, and can access outer class'
private members as regular inner classes do. But the inner class object cannot
use the local variables of the method in which the local inner class is
defined.
The reason why method-local-inner class cannot use
local variables of the method because the local variables of the method are
kept on the stack and perish as soon as the methods ends. But even after the
method ends, the local inner class object may still be alive on the heap.
Method-local-inner class can still use the local variables that are marked
final, any idea why? I am leaving it for your exercise.
The following piece of code demonstrates you the
scope and use of method-local-inner class. Though the given piece of code will
not compile unless you comment or remove System.out.println(y); statement. It
is because local inner class cannot access the method's local variable unless
they are declared final.
* File
: MethodLocalInnerClassDemo.java
* File Description : Demonstrates scope and use of
method-local-inner class
class MyOuter
{
private
int x = 10;
public
void createLocalInnerClass()
{
int y
= 20;
final
int z = 30;
class
LocalInner
{
public void accessOuter()
{
System.out.println(x);
System.out.println(y); //Error: Cannot refer to a non-final variable y
inside an inner class defined in a different method.
System.out.println(z);
}
}
LocalInner li = new LocalInner();
li.accessOuter();
}
}
public class MethodLocalInnerClassDemo
{
public
static void main(String[] args)
{
MyOuter mo = new MyOuter();
mo.createLocalInnerClass();
}
}
NOTE:
It is significant to note that a method-local-inner
class cannot be marked public, private, protected, static, or transient. Because
it is by default local to a method. The only modifiers you can apply to a
method-local-inner class are abstract, and final, but never both at the same
time, else your local inner class will be of no use.
No comments:
Post a Comment