在大多数情况下,我看到嵌套类是static
.
让我们举个例子Entry
上课于HashMap
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
.....
.....
}
Or Entry
类的LinkedList
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
.....
.....
}
到目前为止我对嵌套类的了解是:
- A non-static nested class has full access to the members of the class
within which it is nested.
- A static nested class cannot invoke non-static methods or access non-
static fields
我的问题是,在 HashMap 或 LinkedList 中将嵌套类设为静态的原因是什么?
更新1:
Following the already answer link I got an answer - Since And since it does not need
access to LinkedList's members, it makes sense for it to be static - it's a much
cleaner approach.
Also as @Kayaman pointed out: A nested static class doesn't require an instance of
the enclosing class. This means that you can create a HashMap.Entry by itself,
without having to create a HashMap first (which you might not need at all).
我认为这两点都回答了我的问题。感谢大家的意见。
嵌套静态类不需要封闭类的实例。这意味着您可以创建一个HashMap.Entry
本身,无需创建HashMap
首先(您可能根本不需要)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)