1

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.

8
  • I don't really get it, what do you mean by can I say? In this case, closeAction is instantiated by an abstract inner class, yes. Commented Feb 8, 2014 at 15:34
  • @Merguez: Anonymous, not abstract. The class created is concrete. Commented Feb 8, 2014 at 15:38
  • Whoops, sorry, wrong wording. Commented Feb 8, 2014 at 15:40
  • 1
    The author would have to define what he means with "Local"/"Non-local". If by local he only means "defined inside a method", then he's wrong. Commented Feb 8, 2014 at 15:54
  • 1
    Your example is in fact "local" because field initializer expressions become part of the constructor(s) when the class is compiled. You could say that the local/non-local distinction is between classes that are defined in code that is executed and classes that are defined directly as members of another class (in your case the instance of the anonymous class is a member of the container, but the class itself isn't). Commented Feb 8, 2014 at 15:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Or rather, an anonymous class implementing the ActionListener interface.
Mb I am a bit not clear. I have read that inner classes can't be anonymous. Is it an inner class?
Only inner classes can be anonymous, actually.
Updated question. Can you check please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.