开发者

What are the uses of inner classes in Java? Are nested classes and inner classes the same? [duplicate]

开发者 https://www.devze.com 2023-01-01 09:00 出处:网络
This question already has answers here: Closed 12 years ago. 开发者_运维技巧Possible Duplicate: Java inner class and static nested class
This question already has answers here: Closed 12 years ago.
开发者_运维技巧

Possible Duplicate:

Java inner class and static nested class

What are the uses of inner classes in Java? Are nested classes and inner classes the same?


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


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

What are the uses of inner classes in Java? Are nested classes and inner classes the same? [duplicate]


Related questions

  • Java inner class and static nested class
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号