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 herethis 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()); } } 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net