What's the advantage of making an inner class as static with Java?

后端 未结 6 1220
梦毁少年i
梦毁少年i 2020-12-13 18:21

I have an inner class in my Java class.

\"enter

When I run find bugs, it recom

6条回答
  •  囚心锁ツ
    2020-12-13 19:28

    A static inner class is a semantically simpler thing. It's just like a top-level class except you have more options for visibility (e.g. you can make it private).

    An important reason to avoid non-static inner classes is that they are more complex. There is the hidden reference to the outer class (maybe even more than one). And a simple name in a method of the inner class may now be one of three things: a local, a field, or a field of an outer class.

    An artifact of that complexity is that the hidden reference to the outer class can lead to memory leaks. Say the inner class is a listener and could be a static inner class. As long as the listener is registered, it holds a reference to the instance of the outer class, which may in turn hold on to large amounts of memory. Making the listener static may allow the outer instance to be garbage collected.

提交回复
热议问题