tags:

views:

1987

answers:

6

What is the use of anonymous classes in java? Can we say that usage of anonymous class is one of the advantages of java?

+2  A: 

You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.

The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.

They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.

I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.

Uri
+7  A: 

By an "anonymous class", I take it you mean anonymous inner class.

An anonymous inner class can come useful when making an instance of an object which certain "extras" such as overloading methods, without having to actually subclass a class.

I tend to use it as a shortcut for attaching an event listener:

button.addActionListener(new ActionListener() {
    public void actionPerfored(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.

coobird
Or you could refactor duplicate anonymous inner classes into one method with the anonymous inner class (and possibly some other duplicated code).
Tom Hawtin - tackline
+3  A: 

They're commonly used as a verbose form of callback.

I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)

Here's a swing example

myButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here...
    }
});

Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)

madlep
+1  A: 

Yes, anonymous inner classes is definitely one of the advantages of Java.

With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.

But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).

Lars A Frøyland
+2  A: 

Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:

public interface F<A, B> {
   public B f(A a);
}

You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:

public static int larger(final List<Integer> ns, final int i) {
  for (Integer n : ns)
     if (n > i)
        return n;
  return i;
}

And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:

public static int smaller(final List<Integer> ns, final int i) {
   for (Integer n : ns)
      if (n < i)
         return n;
   return i;
}

These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:

public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
   for (T t : ts)
      if (f.f(t))
         return t;
   return z;
}

You can use an anonymous class to use the firstMatch method:

F<Integer, Boolean>() greaterThanTen = new F<Integer, Boolean> {
   Boolean f(final Integer n) {
      return n > 10;
   }
}
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);

This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.

A nice library for programming Java in this style: Functional Java.

Apocalisp
unfortunately, the verbosity of doing functional programming in java, IMHO, outweights its gains - one of the striking points of functional programming is that it tends to reduce code size, and makes things easier to read and modify. But functional java doesnt seem to do that at all.
Chii
All the understandability of functional programming, with the terseness of Java!
Adam Jaskiewicz
In my experience, functional style in Java is paid for with verbosity up front, but it yields brevity in the long run. For example, myList.map(f) is considerably less verbose than the corresponding for-loop.
Apocalisp
A: 

I use them sometimes as a syntax hack for Map instantiation:

Map map = new HashMap() {{
   put("key", "value");
}};

vs

Map map = new HashMap();
map.put("key", "value");

It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the parent class needs to be serialized via remoting.

Chase Seibert
To be clear, the first set of braces is the anonymous inner class (subclassing HashMap). The second set of braces is an instance initializer (rather than a static one) which then sets the values on your HashMap subclass. +1 for mentioning it, -1 for not spelling it out for the noobs. ;-D
Spencer K