开发者

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?


  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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜