• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Anonymous class --simple example

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I neeed an simple example without involving awt.
 
Desperado
Posts: 3226
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
More than one Java author that I have read, when they talk about the short history of Java, say that anonymous inner classes were invented in great part to facilitate the Java 1.1 event handling in the AWT.
I am moving this thread to the Java beginner section where it will get more attention.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Being lazy, I got this non-AWT example from the Nested Classes Specification here:
Consider a method myEnumerate() which is responsible for returning an Enumeration of the elements in an array. (Look up Enumeration if you're not familiar with it.) This could be done using a local class as follows:

This can also be done using an anonymous class which does the exact same thing:

Study the differences in syntax carefully. Note that since an anonymous class has no name, it can only be used once, to create exactly one instance of itself. (How can you refer to it again since it has no name?) But if that's not a problem, it can be somewhat shorter to write than a local class.
 
Get me the mayor's office! I need to tell her about this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic