• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is anonymous class  RSS feed

 
Ranjeet Kr Rai
Greenhorn
Posts: 12
Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
thanks.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

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: 1 2 3 (with older links on some of those threads).

See whether those help, and ask again if you don't understand it all.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, Ranjeet.

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?).

[edit]
Campbell beat me to it
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!