Using Method Local Inner Classes

The second type of inner class is the method local inner class (MLIC). The name sez it all. We're talking about a class defined inside of a method body.

The primary difference between a regular inner class and an mlic is that the MLIC cannot use the local variables of the method that contains the inner class definition. Only in the event that local variables or arguments are declared final can an object of an inner class access them.

OuterMethodLocal.java

package net.javagarage.inner;
/**<p>
 * Demos Method Local Inner Class
 * </p>
 **/

public class OuterMethodLocal {
public final int x = 5;
public int outY = 10;

//the method
int someMethod() {
final int inX = 5;
int inY = 10;

class InnerClass {
//do some wicked stuff
int getLucky() {
//return inY; //NO! inY is not final!
//return outY; //OK
return inX;//OK —it's final!
}
}

//instantiate method local inner class
InnerClass inner = new InnerClass();

//call a method while you're at it
return inner.getLucky();

}//END OF someMethod

//I can't do this here—this class
//is only available inside the method!
//InnerClass inner = new InnerClass();

public static void main(String[] ar){
OuterMethodLocal out = new OuterMethodLocal();
System.out.println(out.someMethod());
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.89.18