Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing shadowed final values in method local inner class

 
akhil lalwani
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?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
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?
 
Abimaran Kugathasan
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!
 
Wouter Oet
Saloon Keeper
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