• 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
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Accessing the new method in the anonymous inner class

 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If we create a new method in an anonymous inner class then how will we invoke that method as we can't use the instance of the super class.

Please explain with an example.
 
Ranch Hand
Posts: 814
Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Indra

See the following code



Output is : Annonymous

But here method doIt() overrided in annonymous sub class of AnnonymousAccess class.
At line number 8 we used reference of super class to access the overrided method of annonymous inner class.

Let see what other say about your query.
 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

indra negi wrote:
If we create a new method in an anonymous inner class then how will we invoke that method as we can't use the instance of the super class.

Please explain with an example.



If you can't use the super class (or an interface) to call the method, then your only option is to use reflection, as the definition of the anonymous class will be out of scope.

Here's a quick modification of the previous example, that uses refection instead...



Henry
 
Ninad Kulkarni
Ranch Hand
Posts: 814
Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry

The complete code is given below so other can run the program.

 
Sheriff
Posts: 9709
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Anyone pursuing SCJP can relax as Reflection is not on the SCJP objectives
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic