Friday, June 22, 2007

inner, nested, anonymous classes

0 There is no such thing as a static inner class. There are top-level classes and nested classes, and nested classes are by definition divided into static and inner.
0 If it is static, it is not inner class, you can use it just as top-level class, but put a qualifier as EncloseingClass.EnclosedClass.
0 If inner class is a member of enclosing class, it must be attached to an instance of the Enclosing class, something like new EnclosingClass().new EnclosedClass().
0 Local and anonymous classes are also inner classes, they can be defined in methods, initializers, which will be local to that enclosing scope.
0 Since the scope can be instance or static, Local and anonymous classes can be defined in an instance or a static context.

0 inner class in an interface?
interface IFace {
public class X { //It is not member inner class
void method_Of_X() {
System.out.println("Without static modifier, it is still static nested class.");
}
}

static class S { // static nested class.
void method_Of_S() {
System.out.println("static nested class.");
}
}
}
Conclusion: All classes defined in an interface are implicitly static

0Anonymous class always extends the class or implements the interface after the keyword new. I assume that extends or implements can only be implicit, in case of anonymous classes.

0 An anonymous class object can access static and instance fields when it has an associated instance of the enclosing class (i.e. defined in a instance method).
0 An anonymous class can only access static fields when it is in a static context (i.e. defined in a static method).
0 What it can't access is local variables (unless they are declared final). Attention: parameters passed to the method are treated the same as local variables, since it is passed by value and a local copy are really being used.
0 local class defined in a method can access final local variables.

No comments: