Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local inner class

I have read through inner class tutorial and don't understand one thing. It is being said that inner class holds hidden reference to outer class, so I come up with several questions via this plain class:

public class OuterClass {

public void doSomething() {
    JButton button = new JButton();
    button.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {                
      }
    });
  }
}

So we have one local inner class which resides inside method doSomething() and I have some questions involved.

  1. Does this local inner class hold reference to OuterClass since it's local?

  2. Does this local inner class remain memory after the method doSomething() terminates?

  3. Is there any situation in which OuterClass is eligible for GC but local inner class still be referenced by other classes? What would happen?

like image 515
MinhHoang Avatar asked May 30 '11 09:05

MinhHoang


1 Answers

  1. Yes, the inner class has a reference to the OuterClass instance.

    You can verify that by accessing OuterClass.this in the method.

  2. Yes, the inner class instance will continue to exist after the method terminates.

    Leaving the method does not influence the life-time of the object. Just as every other object, it will become eligible for GC once there are no more references to it. Since the JButton will hold a reference to it, it will stay in memory.

  3. The OuterClass instance can't become eligible for GC as long as the inner class instance is reachable.

    The reason for that is #1: the inner class instance has a reference to the outer class instance, which means that the outer class can not become eligible for GC as long as the inner class is not eligible at the same time (i.e. both are no longer reachable).

like image 66
Joachim Sauer Avatar answered Oct 04 '22 20:10

Joachim Sauer