This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Anonymous classes as return statements. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous classes as return statements." Watch "Anonymous classes as return statements." New topic

Anonymous classes as return statements.

Mikael Saltzman

Joined: Dec 07, 2012
Posts: 9
Hello Everybody!

I've just introduced myself to anonymous classes. All worked according to plan until I tried to use pass it to another class using a getter method. So, assume you have a private Iterator = null as a field that you initialize as an anonymous class in the constructor -- is it possible to use this field outside the class in any way? I tried using Object as getter return statement but that did not work.
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

Yes, you can take an instance of an anonymous class and pass it around like any other Object. You would only be able to use it as the type which you pass it as or as some Type it extends or implements, so keep that in mind. For example, here is one using an ActionListener implementation...

And welcome to the Ranch!

Emanuel Kadziela
Ranch Hand

Joined: Mar 24, 2005
Posts: 187
Mikael Saltzman

Joined: Dec 07, 2012
Posts: 9
@Steve: Thanks ever so much! This was really helpful. There were 2 minor minor typos your code though: a final being assigned a value twice and "@Override" written "@Overrides" but it was nevertheless very helpful; plus, a reminder for me how final fields work

@Emanuel: Thank you for this relevant topic addition!

It seems funny in a way how the second (re-referenced?) anonymous class only includes the overridden methods from the particular interface or class it is created with. I mean, such flexibility is probably great but I guess it makes it impossible to access additional methods (non-overridden ones). It would be nice to be able to copy the whole structure without worrying about the class&interface limitations. I guess this is not possible as there is nothing to reference in a non-overridden method belonging to an anonymous class.

Thanks again!
I agree. Here's the link:
subject: Anonymous classes as return statements.
jQuery in Action, 3rd edition