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

寵の児 提交于 2019-12-18 11:09:48

问题


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?


回答1:


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


Related questions

  • Java inner class and static nested class



回答2:


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



来源:https://stackoverflow.com/questions/2941682/what-are-the-uses-of-inner-classes-in-java-are-nested-classes-and-inner-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!