- 1
Why we use anonymous class?
2 Respostas
+ 1
anonymous classes enables us to declare and instantiate the class at the same time.. they are like local classes but they won't have name. we use anonymous classes if we need to use a local class only once
+ 1
Via an anonymous class you can make an instance of an object and implement its overloading methods.
On other words you can instantiate an anonymous class without making a separate class.
This is commonly used in Android programming.
For example in below is a snap of instializing the On Click event of a button
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Here the inner class which actual an interface has one method called void onClick(View v) which is implemented when creating an new instance.
the interfce definishing is as follows:
public interface OnClickListener {
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
void onClick(View v);
}
A simple example to illustrate this concept:
http://code.sololearn.com/c1AJXT1yaoWw/#java
public class Main {
public static void main(String[] args) {
String word = "tiger";
String text = " There is a tiger in the zoo";
Search search = new Search();
search.find(word, text, new Search.OnFinishEvent() {
@Override
public void onResult(boolean isFound) {
if (isFound) {
System.out.println("Found");
} else {
System.out.println("Not Found");
}
}
});
}
}
class Search {
public void find(String word, String text, OnFinishEvent event) {
boolean isFound = (text.indexOf(word)) != -1;
event.onResult(isFound);
}
interface OnFinishEvent {
void onResult(boolean isFound);
}
}