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

后端 未结 6 1287
梦毁少年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:10

    An inner class, by default, has an implicit reference to an object of the outer class. If you instantiate an object of this from the code of the outer class, this is all done for you. If you do otherwise you need to provide the object yourself.

    A static inner class does not have this.

    That means it can be instantiated outside the scope of an outer class object. It also means that if you 'export' an instance of the inner class, it will not prevent the current object to be collected.

    As a basic rule, if the inner class has no reason to access the outer one, you should make it static by default.

提交回复
热议问题