Thursday, September 26, 2013

Java: Anonymous Inner class




Anonymous Inner class

 

Note :Used in conjunction with Abstract Class or Interfaces

Example :

public class Test1 {

    public static void main(String[] args) {

        x obj=new x(){
                void disp() {System.out.println("Hi");}
                };
        obj.disp();
    }

}


abstract class x{   
    abstract void disp();
}

 

 Output: Hi

 


Use it as a shortcut for attaching an event listener:

Example:

button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)

    {

        // do something.

    }

});


  • Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener --
  •  I can just instantiate an anonymous inner class without actually making a separate class.
  • I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.



No comments:

Post a Comment