Question

Let's assume I need a specific application-wide actionListener. For example:

public class TestAnonymousInnerClass {
    private ActionListener closeAction = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }
    ...
}

This code compiles and works fine, but can I say that I have used an anonymous inner class to instantiate this closeAction field?

UPD: I am reading the book SG Ganesh, Tushar Sharma - Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805 (The Expert's Voice in Java) - 2013 And here is the confusing illustration: enter image description here As follows it is not possible to have anonymous and 'non-local' class. But my class seems to be of that kind because it is not in context of method and still anonymous.

Was it helpful?

Solution

Yes, You have created a annonymous inner implementation class of ActionListener interface. And instantiate it and assigned to closeAction variable

In short we can say that an anonymous class is an inner class that does not have a name at all. And whose instance is being created at the time of its creation. Check here for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top