Hello, to everybody
i am new to java and i was going though some of the java topic in websites there i found anonymous class. i really confusing to me please give some example regarding to this.
It is a class created, often from an interface, but no name is given to it. You can override any of the methods, but cannot create a new constructor. Examples for Runnables in the API, and for Listeners: 123 (with older links on some of those threads).
See whether those help, and ask again if you don't understand it all.
Anonymous classes are nameless classes that you define as you need them. They are often used in multi-threading and event handling. Here is an example:
Arrays.sort() requires an instance of Comparator<T> in order to sort the array. We could create a new class that implements Comparator in the usual way, but sometimes an anonymous class is more succinct.
In this example, we create a nameless class that implements Comparator<Object>, and we create an instance of that class and assign it to compare.
Note than an anonymous class only ever allows you to have a single instance of it (how can you make more instances if you don't know what the class is called?) and that they can not have custom constructors (how can you make a constructor if you don't know what the class is called?).
Campbell beat me to it
He was giving me directions and I was powerless to resist. I cannot resist this tiny ad: