6

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.

2
  • it's static because a Node<E> of one List<E> can be the same type as the nodes from every other List<E>. The type does not need to be bound to a single List<E> instance. Commented Jan 3, 2017 at 7:41
  • @PatrickParker Thanks, it's helpful. Commented Jan 3, 2017 at 7:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the example, really make it easy to understand. The Node<E> type does not need to be bound to a single List<E> instance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.