• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Passing 'this' reference implicitly via the anonymous inner class.

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone!

I'm currently learning Java and reviewing best practices( javapractices.com ) and stumbled on the topic of passing 'this' out of a constructor. I more or less understood that we mustn't do it, but I can't understand how we are passing 'this' reference implicitly via the anonymous inner class in this example:


How is anonymous inner class related to 'this' object?
 
Saloon Keeper
Posts: 14266
321
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

Line 14 is a shorthand for this.doSomethingUseful().

Technically it's possible for the Observable to notify your anonymous observer of an event before the constructor has finished running.
 
Bartender
Posts: 5061
188
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Line 14 is a shorthand for this.doSomethingUseful().


Slight correction: the 'this' relates to the new Observer. So if you want to use a this reference, you should get:
 
Trevor Philips
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks! This coffee (java) gets me lightheaded every time I try to drink too much of it..
 
It would give a normal human mental abilities to rival mine. To think it is just a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic