Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of Anonymous Inner Class (over non-anonymous inner class)?

Consider this (anonymous):

speakBtn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        mTts.speak(words.getText().toString(), TextToSpeech.QUEUE_ADD, null);
    }});

vs. this: (non-anonymous):

class MyOuterClass {
    private class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View view) {
            mTts.speak(words.getText().toString(), TextToSpeech.QUEUE_ADD, null);
        }
    }

    // later (inside some method)...
        speakBtn.setOnClickListener(new MyOnClickListener());
}

Except for the fewer number of lines, is there any other advantage to the anonymous form?

Is there a performance advantage?

like image 299
an00b Avatar asked Feb 28 '11 22:02

an00b


People also ask

What is the advantage of anonymous class in Java?

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.

What is anonymous inner class explain the advantage of using anonymous inner class with an example?

It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.

What is the difference between anonymous class and inner class?

A local inner class consists of a class declared within a method, whereas an anonymous class is declared when an instance is created. So the anonymous class is created on the fly or during program execution.

What are the advantages of inner class?

Inner classes are used to develop a more readable and maintainable code because they logically group classes and interfaces in one place. Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to write. It can avoid having a separate class.


1 Answers

The anonymous inner class has advantage over the inner class (as in the question example code) in that it closes over the local variables of the method (although only final locals are usable).

Generally an inner class can be easily converted into a method with anonymous inner class, which helps reduce verbosity. If you've got an inner class that is so large that you want to make it non-local, you might want to think about battling with your IDE to put it in a new file as an outer class.

(The is also local classes, which are normal named inner classes defined within a method and that close over locals.)

like image 155
Tom Hawtin - tackline Avatar answered Sep 19 '22 18:09

Tom Hawtin - tackline