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?
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With