| Author |
accessing shadowed final values in method local inner class
|
akhil lalwani
Greenhorn
Joined: Aug 21, 2010
Posts: 5
|
|
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
Joined: Jul 08, 2003
Posts: 24054
|
|
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?
|
[Jess in Action][AskingGoodQuestions]
|
 |
Abimaran Kugathasan
Ranch Hand
Joined: Nov 04, 2009
Posts: 2066
|
|
|
No way if you shadow it!
|
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
If you make the variable y an instance variable than you can access it with MyOuter.this.y.
And please UseCodeTags when posting code.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
akhil lalwani
Greenhorn
Joined: Aug 21, 2010
Posts: 5
|
|
|
I just asked it out of curiosity. Anyways thanks for the help.
|
 |
 |
|
|
subject: accessing shadowed final values in method local inner class
|
|
|