Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Inner class data access

 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Below is code with a method-local inner class. The outer class, the method in which the inner class is defined and the inner class itself have a final attribute called string. How can you access the string defined in the method in this case?


This prints
default string : Private attribute of inner class
this.string : Private attribute of inner class
InnerTest.this.string : private outer string

as expected. So how do u explicity reference the other string to print
"Method defined string"? It is possible at all??

//Tom



( tags added)
[ May 16, 2005: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I do not think you can. The variable string in the testInner method is hidden by that class variable string defined in the method local class.

I suspect that there may be some tricky stuff possible using reflection but that's beyond the scope of SCJP.
[ May 16, 2005: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


In the above, I have added a constructor which smuggles the method's string into the state of the inner class. Then you can access it from within the method InnerTestStrings. Mucky though.
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yep that indeed will work since the method local variable shadows the outer class variable....but as you say its awkward. Dont really think the above situation arises very often anyways as it is bad naming convention, but wondering was there a way to do it
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic