• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

accessing shadowed final values in method local inner class  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code:

class MyOuter
{
private String x = "abc";
void doStuff( )
{
final int y = 10;
class MyInner
{
int y = 20;
void seeOuter( )
{
System.out.println("String is " + x);
System.out.println("y is " + y);
}
}
MyInner in = new MyInner( );
in.seeOuter( );
}
public static void main(String[ ] args)
{
MyOuter obj = new MyOuter( );
obj.doStuff( );
}
}


How do i access the final y declared at the beginning of method doStuff( ), inside the seeOuter( ) method of inner class MyInner?
 
author and iconoclast
Sheriff
Posts: 24220
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't; there's no syntax that allows you to single out a particular local variable like that.

But why would you do this -- if you are writing the inner class, you can just rename its member variable, right?
 
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No way if you shadow it!
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you make the variable y an instance variable than you can access it with MyOuter.this.y.
And please UseCodeTags when posting code.
 
akhil lalwani
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just asked it out of curiosity. Anyways thanks for the help.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!