0
I don't understand what anonymous classes are...
3 Respostas
+ 1
Ok
0
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 commany 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);
}
}
0
its Simply to Change the method definition in main method without creating a new class.