How using static inner class avoids memory leakage?

2.7k views Asked by At

I have read that non-static inner class can make more memory leaks than static inner class. It is fine that non-static class will produce object instance of itself as well as its out class as reference to it.

So static inner class can avoid multiple object instances because it will create single class level object and not instance level. But how can it avoid creating objects of instances of its outer class?

Plz help understanding static inner class vs non-static/anonymous inner class memory leakage.

1

There are 1 answers

0
Pradeep On

The static/non static inner class is a bit complex, and explained in detail in the other question(link in comments) I will try to answer your question here

But how can it avoid creating objects of instances of its outer class? It does not avoid, you can still create the object of outer class

The difference it makes is, as static class does not keep reference to outer class, the object of outer class cannot be kept alive by inner class object.

While in case of non static one, there will be a reference to outer class and till the time you have alive reference to inner class object(say O1), outer class objects (which are referred by O1) will also not be garbage collected (even if you may not be having any live reference of outer class object).