7

In package java.util.LinkedList, the Class Node defined as one static class, is it necessary? What is the goal?

We can find source code from this page.

Ivan
  • 661
  • 1
  • 8
  • 15

1 Answers1

8

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.

Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
  • Thanks for the example, really make it easy to understand. The Node type does not need to be bound to a single List instance. – Ivan Jan 03 '17 at 07:52