What is the reason for making a nested class static in HashMap or LinkedList? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-06 00:56:42

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).

1) Because it is not needed from the "outside": it is only used by the enclosing class. By making it a private inner static class, this intention is obvious.

2) By being an inner class, it automatically has access to all private fields of the enclosing class, so there is no need to create getters or worse like making them package private or protected.

And why make it static?

Non-static inner classes need a reference to an instance of the enclosing class. If the inner class is static, this is not needed: instances of static inner classes don't have a reference to the enclosing class. They can be created without an instance of the enclosing type and they can live without it.

In case of non-static inner class, the instance of the enclosing class is sometimes transparent (e.g. when you instantiate the non-static inner class from a non-static method of the enclosing class, it is this), or can be explicit, e.g.:

EnclosingClass ec = new EnclosingClass();
InnerClass ic = ec.new InnerClass();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!