• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

what is anonymous class

 
Greenhorn
Posts: 12
Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 76416
365
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Saloon Keeper
Posts: 14273
321
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
He was giving me directions and I was powerless to resist. I cannot resist this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic