13

I run into some code which contains anonymous classes. I haven't met with anonymous classes before, so I did some research on them.

My main area of interest is java, so I checked Oracle's tutorial of anonymous classes. I understand the mechanism and I see the point of the examples but in my opinion using anonymous classes makes the code hard to read and can cause a lot of headache.

Are there any cases when it is unavoidable to use anonymous classes or it is advised to use them instead of named classes?

Tamas G.
  • 677
  • 3
  • 21
  • 38
  • 2
    the doc says: Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once. – guillaume girod-vitouchkina Nov 30 '15 at 11:09
  • 3
    I agree totally `anonymous` and `inner` classes can make code unreadable and kaotic, but they can also clarify a lot with little needings. They are a tool in your hands, just be wise in your choices. – Jordi Castilla Nov 30 '15 at 11:11
  • 1
    Anon inner classes are one of those proverbial double-edged swords. – biziclop Nov 30 '15 at 11:24

3 Answers3

15

Are there any cases when it is unavoidable to use anonymous classes

No, you can always just use a private inner class instead of an Anonymous class.


using anonymous classes makes the code hard to read and can cause a lot of headache

This very much depends on how you use anonymous classes. Consider the following example:

new Thread(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}).start();

In this example you create a Runnable which is run by a thread. If you wouldn't use an anonymous class you'd have to write it as follows:

private class SomeClass implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
}

and use it as:

new Thread(new SomeClass()).start();

With the first possibility you can directly see what that thread is doing, in the second possibility you'll first have to find the class that is used here.


Another advantage of anonymous classes. You can do the following:

// define some constant which can be used in the anonymous class:
final String someStr = "whatever";

new Thread(new Runnable() {
    @Override
    public void run() {
        // use the String someStr directly
        System.out.println(someStr);
    }
}).start();

You can use the constant which is declared in the code where the anonymous class is defined. If you'd use a private inner class you'd have to give these constants to the constructor of the class in order to use them!

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
5

You can always avoid using of anonymous classes by defining new class implicitly. However in some cases it's better to use anonymous classes. Consider following example:

void main() {
   new Thread(new Runnable(){
      public void run() {
        System.out.println("Hello world");
      }
   }).start();
}

Code snippet above is more readable and shorter then defining new class.

public class MyRunnable implements Runnable {
   public void run() {
     System.out.println("Hello world");
   }
}


void main() {
   new Thread(new MyRunnable()).start();
}

In Java 8 labmda can be used instead of anonymous class in some cases

Runnable task = () -> { System.out.println("hello world"); };
new Thread(task).start();
Anton
  • 5,831
  • 3
  • 35
  • 45
  • Lambdas are not related to Anonymous class concept, but to Functional interface (an interface with only one method). – Prim Nov 30 '15 at 11:17
  • 3
    @Prim They are very much related, but aren't always interchangeable. – biziclop Nov 30 '15 at 11:19
  • 3
    @biziclop Yes, but the answer says `"In Java 8 labmda can be used instead of anonymous class"` which is incorrect. It's true only when it is an anomynous class which implements a functional interface – Prim Nov 30 '15 at 11:25
3

Are there any cases when it is unavoidable to use anonymous classes...

No. You could always define a named class for that. The point of annonymous classes is to make the code more concise and compact in situations in which you only need to use a class once.

it is advised to use them instead of named classes?

It depends on the context of the class being created.

if you are implementing interfaces having only one function (i.e Runnable) then using lambda expression instead of anonymous classes is not a bad choice. lamba expression