Anonymous Classes in Java


About author  I am Java/oracle professional.Working on Java/J2EE technologies and i.e Java,J2ee,Oracle ADF,hibernate,J2ee,PL/sql,Apps for 4+ years.I am passionate about learning new technologies.I am sharing my knowledge. Give your views and suggestion on vinay@techartifact.com http://www.linkedin.com/in/vinaykumar2 Read more from this author


A type of inner class that has no name that you define right in the middle of a method (where static init blocks and instance init blocks count as methods). You define it, and create an object of that type as a parameter all in one line. An anonymous class is defined and instantiated in a single succinct expression using the new operator.Used for creating simple delegate callback objects.These anonymous inner classes can access the static and instance variables of the enclosing outer class.
Instead of passing arguments to a constructor, your inner class methods can reach out and grab what they need directly from local variables in the enclosing method. The other technique is to use an instance initialiser block. You are only allowed one per anonymous inner class.
Syntax for Anonymous Classes -
new class-name ( [ argument-list ] ) { class-body }

package Vinay;
public class VinayMain
{
public static void main(String[] args)
{
// Here is where the anonymous class is defined and instantiated //
Runnable vinayrun = new Runnable()
{
int Total = 0;
public void run()
{
for (int i=0; i<10000000; i++)
{
Total++;
}
System.out.println(Integer.toString(Total));
 }
 };
vinayrun.run();
}
 }

create an instance, named vinayrun , of a nameless (anonymous) class which implements the java.lang.Runnable interface.And we are calling the run mehtod of anonymous class through vinayrun object.

Drawback– The big drawback with anonymous classes is they can’t have explicit constructors. You can’t pass them any parameters when they are instantiated.

Benefits of Anonymous Classes
The key benefit of an anonymous class is encapsulation (or clutter reduction). An anonymous class is, in a sense, the ultimate in private object oriented encapsulation. It is defined exactly where it is needed, it can never be used anywhere else, and it has totally local scope.One final key benefit of anonymous classes is that they have access to all data and methods of their containing classes, including private members; meaning that for small highly localized tasks, they may require less initialization.

References -

http://ssmela.googlepages.com/AnonymousClassesinJava.pdf

http://mindprod.com/jgloss/anonymousclasses.html

9 Responses to Anonymous Classes in Java


  1. AlexanderNo Gravatar
    Aug 18, 2009

    Wow! Anonymous classes! Did you wake up yesterday after decade being sleeping?
    FYI you can pass parameters in constructor of anonymous class, if appropriate super constuctor exists.


  2. Stewart SmithNo Gravatar
    Aug 20, 2009

    The bug you have here is that you don’t create and start a thread.


    • AnonymusNo Gravatar
      Jan 29, 2012

      too good.


  3. Pravin JainNo Gravatar
    Aug 22, 2009

    “Instead of passing arguments to a constructor, your inner class methods can reach out and grab what they need directly from local variables in the enclosing method.”

    FYI local variables from the enclosing method can be accessed from the methods of the anonymous class only if these are final vairables.


  4. ritu ranjanNo Gravatar
    Jul 30, 2011

    is annonymous class can only override metho or we can declare method inside it?


  5. John RobNo Gravatar
    Nov 23, 2011

    This is one of the best articles I read online. No crap, just useful information. Very well presented. Its really helpful for beginner as well as developer. Check this link too it also having nice collection of java interview question.

    http://www.mindstick.com/Interview
    /1140/What%20is%20Anonymous%20class%20in%20java

    Thanks Everyone for sharing your nice post with us.


  6. Pravin JainNo Gravatar
    Nov 24, 2011

    The anonymous class cannot always access the static members of the enclosing class. This would happen when an anonymous class is defined in a static context, eg. in a static method or the static block.
    Also anonymous class can use constructor of super class to pass parameters at runtime, and we have a workaround for initializing and passing parameters at creating time.
    eg.
    String someName = “some name”;
    Object obj = new Object() {
    String name;
    public init(String s) {
    this.name = s;
    }
    }.init(someName);

    In the above example, instead of Object, you could use any other appropriate super-class.


    • Pravin JainNo Gravatar
      Nov 24, 2011

      The initMethod above should declare a return type of Object, and should add the return this at the end.

Trackbacks/Pingbacks

  1. PimpThisBlog.com

Leave a Reply