Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: Anonymous Code

  1. #1
    New Coder
    Join Date
    Sep 2012
    Location
    Mumbai
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Anonymous Code

    I recently encountered a code in my java program that is as follows..
    Code:
    button.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e)
       {
          //Some action here
       }
    });
    I don't know what is after new ActionListener() but it seems a method of ActionListener is overridden and in some block....huh
    Last edited by Zaid; 01-14-2013 at 11:41 AM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Yeah, this is an anonymous inner class. ActionListener itself is an interface, but since it is being invoked and the entire method set is being declared as a part of the class body, this is valid code. Prior to Java 8, it's also the closest thing we have to a closure in Java.
    So effectively you create an unnamed instance and provide that as the argument. That particular instance can never be used again.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •