Hello all,
I seem to recall that local classes can access all variables of the outer class but only final variables of the enclosing method. Yet when I run the following, it seems the say() method of localClass can access even the non final variables of its enclosing class dummyMethod() in addition to all variables of the outer class.
Whats going on?
import java.awt.event.*;
class anonymousClass
{}
class outer
{
int i=99;
static int j=3;
final int k=98;
class memberClass
{
void say()
{
System.out.println("Can only access instance (non static) variables of the enclosing class. int i: "+i);
System.out.println("A member class cannot be static and cannot have static declarations of methods or variables");
System.out.println("A member class is called through an instance of its enclosing class or via new outer().new inner()\n");
System.out.println("***********************************************************************");
}
}
static class nestedClass
{
static void say()
{
System.out.println("Can only access static variables of the enclosing class. Static int j: "+j);
System.out.println("A nested class is static and all its methods and variables should be declared static.");
System.out.println("A nested class is called via outer.inner as no instance can be created of a static class\n");
System.out.println("***********************************************************************");
}
}
void dummyMethod()
{
int l=21;
final int m=99;
class localClass
{
void say()
{
System.out.println("Local classes cannot have the modifiers public, private, protected or static");
System.out.println("Local classes can only access non static variables of the top level class, int i: "+i);
System.out.println("Local classes can access only static variables of the top level class, static int j: "+j);
System.out.println("Local classes can access only final variables declared in the enclosing method but all");
System.out.println("variables of the top level class: top level variables int i="+i+" static int j="+j+"final k="+k);
System.out.println("and local variables of enclosing method: final int m="+m+". int l cannot be accessed as it is not final");
System.out.println("***********************************************************************");
}
}
new localClass().say();
}
}
public class classes
{
public static void main(String arg[])
{
new outer().new memberClass().say();
outer.nestedClass.say();
new outer().dummyMethod();
}
}