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.
Does this local inner class hold reference to OuterClass since it's local?
Does this local inner开发者_运维百科 class remain memory after the method
doSomething()
terminates?Is there any situation in which OuterClass is eligible for GC but local inner class still be referenced by other classes? What would happen?
Yes, the inner class has a reference to the
OuterClass
instance.You can verify that by accessing
OuterClass.this
in the method.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.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).
精彩评论