When using an anonymous inner class as a PropertyChangeListener at what point in the object life cycle is the class garbage collected? After the containing class (SettingsNode) is reclaimed? Should I explicitly remove the PropertyChangeListener in the finalizer of the containing class (SettingsNode)?
public class SettingsNode extends AbstractNode
{
public SettingsNode(Project project, ProjectSettings projectSettings)
throws IntrospectionException
{
// use an anonymous inner class to listen for changes
projectSettings.addPropertyChangeListener(ProjectSettings.PROP_NAME,
new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
// handle event
}
});
}
}
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.
Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. We may either extend an existing class or implement an interface.
Ans: C Explanation: Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous...
A local inner class consists of a class declared within a method, whereas an anonymous class is declared when an instance is created. So the anonymous class is created on the fly or during program execution.
Like all objects, the anonymous inner class is eligible for garbage collected when the last reference to it no longer references it. I'm using weasel wording here because Java doesn't guarantee that things will be GC'd – the only guarantee is that it won't happen as long as there is a reference.
In this particular case, that would be when projectSettings
either does a removePropertyListener()
or is itself garbage collected.
Because projectSettings
references the anonymous inner class and because the inner class references its containing class, that means the containing class will also live at least as long as the inner class.
You are adding the PropertyChangeListener class you are creating to the projectSettings object. That PropertyChangeListener will not be collected as long as projectSettings references it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With