Thursday, May 20, 2010

How to access method variable in a innser class declared inside method

Variables declared inside a method can be used inside the inner class declared inside this method. But, those variables must be declared as final variables as shown in the below example.


public class InnerClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InnerClass ic = new InnerClass();
ic.inner();
}
public void inner()
{
final int a = 10;
class Inner
{
public Inner()
{
System.out.println(a);
}
}
new Inner();
}
}

Output: 10

2 comments: