aspose file tools*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous classes as return statements." Watch "Anonymous classes as return statements." New topic
Author

Anonymous classes as return statements.

Mikael Saltzman
Greenhorn

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
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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!


Steve
Emanuel Kadziela
Ranch Hand

Joined: Mar 24, 2005
Posts: 186
Mikael Saltzman
Greenhorn

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: http://aspose.com/file-tools
 
subject: Anonymous classes as return statements.