Inner and nested classes are classes defined inside another class or interface. There is no limit at the number of nesting.
The difference between a nested and an inner class is that the inner class keeps a link to its enclosing class so that is has access to the enclosing members.
An inner class is declared by using the 'inner' keyword.
Therefore
- an inner class can only be created by its enclosing class in a non static context (otherwise the link inner-to-enclosing cannot be created).
- creating a nested class is equivalent to creating a class in a different namespace with different access modifiers
Syntax :
public class Enclosing { public class Nested { }
inner public class Inner { } }
Example :
public class SomeClass { private int i;
public class ANestedClass { // as ANestedClass is public one can reference it from the outside // as SomeClass.ANestedClass // Often the nested class is declared private and is used as an helper class }
public SomeInterface f() { return new AnInnerClass(); }
inner class AnInnerClass implements SomeInterface{ // AnInnerClass has access to all private fields/methods of its enclosing class // therefore, one can use the private field i from SomeClass here ... } }
Comments
Keep with Java
Thursday, 11. August 2005 20:33:46, by Vincent
A class declared within another will have an implicit access to the containing class' this, just as your keyword "inner" does.
If a programmer wants to declare a class within another without that implicit this, it should declare the inner class "static" wich is semantically consistent with declaring static fields.
No
Friday, 12. August 2005 09:44:17, by David