Why class Node in LinkedList defined as static but not normal class

This question already has an answer here:

  • Java inner class and static nested class 23 answers

  • Instances of static nested classes have no reference to an instance of the nesting class. It's basically the same as putting them in a separate file but having them as nested class is a good choice if the cohesion with the nesting class is high.

    Non-static nested classsed however require an instance of the nesting class to be created and instances are bound to that instance and have access to it's fields.

    As example, take this class:

    public class Main{
    
      private String aField = "test";
    
      public static void main(String... args) {
    
        StaticExample x1 = new StaticExample();
        System.out.println(x1.getField());
    
    
        //does not compile:
        // NonStaticExample x2 = new NonStaticExample();
    
        Main m1 = new Main();
        NonStaticExample x2 = m1.new NonStaticExample();
        System.out.println(x2.getField());
    
      }
    
    
      private static class StaticExample {
    
        String getField(){
            //does not compile
            return aField;
        }
      }
    
      private class NonStaticExample {
        String getField(){
            return aField;
        }
      }
    

    The static class StaticExample can be instantiated directly but has no access to the instance field of the nesting class Main . The non-static class NonStaticExample requires an instance of Main in order to be instantiated and has access to the instance field aField .

    Coming back to your LinkedList example, it's basically a design choice.

    Instances of Node do not require access to fields of the LinkedList, but putting them in a separate file also makes no sense, as the Node is an implementation detail of the LinkedList implementation and are of no use outside that class. So making it a static nested class was the most sensible design choice.

    链接地址: http://www.djcxy.com/p/92016.html

    上一篇: 为什么java不允许创建内部类的实例?

    下一篇: 为什么LinkedList中的类节点被定义为静态而不是普通类