aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Accessing the new method in the anonymous inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Accessing the new method in the anonymous inner class" Watch "Accessing the new method in the anonymous inner class" New topic
Author

Accessing the new method in the anonymous inner class

indra negi
Ranch Hand

Joined: Aug 12, 2009
Posts: 68

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.
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 802

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.


SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19066
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 802

Thanks Henry

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

Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

Anyone pursuing SCJP can relax as Reflection is not on the SCJP objectives


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
jQuery in Action, 2nd edition
 
subject: Accessing the new method in the anonymous inner class