Inner and Nested classes
You are here :

Sub nodes

Recent changes
Site plan

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.


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 ...
Propulsed by Wiclear


Keep with Java

Thursday, 11. August 2005 20:33:46, by Vincent

I think Java idea for inner class are semantically better.

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.


Friday, 12. August 2005 09:44:17, by David

Ask to beginners if they know of "static nested classes". Most of the time, the answer will be no. They even won't be able to tell the difference between a nested and an inner class. Then ask them what they think they're doing when they are creating a nested class in Java ? Most will answer "I'm creating an helper class". Thus more skilled programmers will answer "then, make it static". What I mean is Java's nested and static nested classes needs a little understanding and use : it's not intuitive. By making the distinction with the "inner" keyword, Nosica tries to adress this point. Nested classes are designed to be helper classes (90% of all uses, the intuitive case), while it is still possible to make a real inner class with the "inner" keyword.