Monday, July 27, 2009

Java nested classes

I usually get confused with nested classes so I'll note some important points here.

Nested classes
- is also a member of enclosing class like variables and methods
- can use all access modifiers like variables and methods

Types of nested classes
1) static
- like a static method, it is not associated to any instance of enclosing class and has access only to all the static members
- syntax: Outer.Inner i = new Outer.Inner();

2) non-static / inner
- has access to other members of enclosing class even if declared private
- like non-static methods, it cannot define any static members as static members only belong to the (outer) class
- syntax: Outer.Inner i = new Outer().new Inner();

3) local inner - declared and known only within the body of method/block

4) anonymous inner - no name and known only within the statement in w/c they are defined

No comments:

Post a Comment