Saturday, 10 September 2016

Java | Anonymous Inner class

Anonymous Inner class

An inner class declared without a class name is known as anonymous inner class. In case of anonymous inner classes we declare and instantiate them at the same time. Generally they are used whenever you need to override the method of a class or an interface.
Anonymous inner classes are declared without any name at all. They are created in two ways.
  •     An subclass of specified type

Class demo
   {
      Void show()
           {
                 System.out.println(“show method of super class”);
           }
   }
Class flavour1 demo
    {
//An anonymous class with demo as base class
Static demo d= new demo()
    {
Void show()
       {
                 Super.show();
                  System.out.println(“I am in flavour1 demo class”);
        }
   };
Public static void main(String[] args)
     {
d.show();
      }
}
}

  Output :       

  show method of super class
   I am in flavour1 demo class

 
                      

In above code demo act as super class and anonymous class act as a subclass. Both have show() method. In anonymous class show() method is overridden

  •      As implementation of specified interface

 Interface hello
      {
             Void show();
       }
Class helloworld
  {
//An anonymous class that implements Hello interface
Static Hello h = new Hello()
    {
          Public void show()
                  {
               System.out.println(“ Anonymous class”);
             }
};
Public static void main(String[] args)
{
h.show();
}
}

 Output :

  Anonymous class                       
                                 
 
                       
In above code we can create an object of anonymous inner class but this anonymous inner class is an implementer of the interface Hello. Any anonymous inner class can implement only one interface at one time. It can either extend a class or implement interface at a time

Advantages of anonymous inner class:

·         Generally an inner class can be easily onverted into a method with anonymous inner class, which helps reduce verbosity
·         The advantage to non-anonymous is that you can resues the clad. I believe the only reason to use an anonymous inner class is brevity
·         One advantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used.
·         Anonymous inner classes are hard to debug in Eclipse.
·         The key benefit of an anonymous class is encapsulation (or clutter reduction)






Class demo    {

Void show()     

No comments:

Post a Comment