views:

145

answers:

2

Possible Duplicate:
Java inner class and static nested class

what is the use of inner classes in java ? is nested classes and inner classes are same?

+6  A: 

No, they're not the same: an inner class is non-static.

JLS 8.1.3 Inner Classes and Enclosing Instances

An inner class is a nested class that is not explicitly or implicitly declared static.

Consult also the following diagram from Joe Darcy:

Joseph D. Darcy's Oracle Weblog - Nested, Inner, Member, and Top-Level Classes

alt text


Related questions

polygenelubricants
+2  A: 

The difference is well addressed by the other answer. Regarding their usage/relevance, here is my view:

Anonymous class: handy for productivity

They are handy to implement callbacks easily, without the burden to create new named class.

button.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent e ) {
              frame.dispose();
         }
      }
);

They are also handy for threading (e.g. anonymous Runnable) and a few other similar pattern.

Static nested class: handy for encapsulation

Static nested classes are essentially like regular classes, except that their name is OuterClass.StaticNestedClass and you can play with modifier. So it provided some form of encapsulation that can not exactly be achieved with top-level classes.

Think for instance of a LinkedList for which you would like the class Node (used only internally) to not be visible in the package view. Make it a static nested class so that it's fully internal to the LinkedList.

Inner class: handy for ownership and encapsulation

An instance of an inner class has access to the field of its enclosing class instance. Think again of the linked list and imagine Node is an inner class:

public class LinkedList {
  private Node root = null;

  public class Node {
    private Object obj;
    private Node next;

    ...

    public void setAsRoot() {
       root = this;
    }
  }

  public Node getRoot() {
    return root;
  }

  public void setRoot( Node node ) {
    root = node;
  }

}

Each Node instance belonging to a LinkedList can access it directly. There is an implicit ownership relationship between the list and its nodes; the list owns its nodes. The same ownership relationship would require extra code if implemented with regular classes.

See Achieve better Java code with inner and anonymous classes

ewernli