Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing the new method in the anonymous inner class

 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • 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.
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Hibernate Linux Spring
  • Mark post as helpful
  • send pies
  • 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.
 
Henry Wong
author
Marshal
Pie
Posts: 20894
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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: 802
Hibernate Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry

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

 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anyone pursuing SCJP can relax as Reflection is not on the SCJP objectives
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic