Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

Android Memory Leak management says "Don use non-static inner classes" but this comes with a side effect

Lets say I have an inner class that I make static, so I avoid memory leaks. Now, this inner class wants to use a method from the main class, but in order for me to do that, I need to make that method static as well because "you cannot use non-static method in a static context". And if I make that method static, the fields that it uses should also become static and now a chain reaction is triggered, where everything should be changed to static, which I do not like.

public class MyFragment extends Fragment {

    private int field1;
    private int field2;


    private void doSomething() {
        field1 + field2;

    }

    private class CertainListenerImpl implements CertainListener {

        @Override
        private void onCertainEventsOccurrence() {
             doSomething();
        }


    }


}

If I change the inner class in the forementioned code to "static" now I have to make doSomething be static and also field1 and field2 be static.

What do I do?

Upvotes: 0

Views: 230

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533472

non-static classes can lead to unintended references to outer classes. In your case you could pass in a reference to an outer class which would make it clearer as to what you are doing but also make your code more complex. There is no wrong or right, I suggest you do what you believe will be less error prone.

I have to make doSomething be static and also field1 and field2 be static.

I wouldm't do that. Instead you can pass the instance of MyFragment to the constructor to CertainListenerImpl and store this as field, which is what Java does for you.

BTW: This internal field is called this$0 for the Oracle/OpenJDK, and if you create a field with this name it will call it this$$0 or with more $$$$

What you have now is equivalent to

private static class CertainListenerImpl implements CertainListener {

    private final MyFragment this$0; // rename to taste

    CertainListenerImpl(MyFragment myFragment) {
        this$0 = myFragment;
    }

    @Override
    private void onCertainEventsOccurrence() {
         this$0.doSomething();
    }


}

Upvotes: 1

Related Questions