Why are the inner classes of data structures in java static?

this is the internal Node of LinkedList

private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

this is the internal Node of HashMap

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }
}
Aug.16,2021

static's inner class, is actually a normal class, just packaged with its outer class to make it easier to write and name, that's all. If you don't use static, here, it's more complicated. Non-static inner class has references to its outer class, so you need to consider more usage issues. In short, static's inner class should be preferred.


is declared as static so that this inner class can be inherited by the inner class of other classes (for example, the inner class Entry of LinkedHashMap inherits from the Node class of HashMap). If it is not declared as static, it cannot inherit

for a non-static inner class, this inner class actually belongs to an external class object. When creating an internal class object, it is created in the way of external class object .new. When declared as static, this inner class belongs directly to the external class.

declared that default is used by other classes of the exclusive java.util package. On the other hand, if it is protected or public, other external classes inherit this external class so that its inner class can inherit the non-static inner class of this external class, and it does not need the static keyword to inherit. Then default and static are not used here and have no meaning

non-static inner class in the class library. The main purpose is to use the external class. this to operate the external class objects in the inner class or to manipulate the properties of the outer class in the inner class. These inner classes are all private declarations, because the inner class that is not declared by static cannot be directly inherited by other internal classes, and the inner class does not need to be accessed externally, so it is only natural to use private

and some of them are already private. Why add static ? The non-static inner class actually belongs to the object of an external class. After adding static, the inner class directly belongs to the external class, belongs to the content of the class level, and does not need to access the content of the external class. The inner class of static should belong to the standard inner class, which is more in line with its definition and meaning

.
Menu