I don't understand what anonymous classes are... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I don't understand what anonymous classes are...

11th Sep 2016, 4:20 PM
violet
3 Answers
+ 1
Ok
11th Sep 2016, 5:57 PM
violet
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); } }
11th Sep 2016, 5:10 PM
Tiger
Tiger - avatar
0
its Simply to Change the method definition in main method without creating a new class.
20th Sep 2016, 4:04 AM
Akash Metange
Akash Metange - avatar