This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous classes as return statements.

 
Mikael Saltzman
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 187
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Mikael Saltzman
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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!
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic