Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes accessing shadowed final values in method local inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "accessing shadowed final values in method local inner class" Watch "accessing shadowed final values in method local inner class" New topic
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: 24183
    
  34

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
 
Similar Threads
Code for Method-Local Inner Classes not compiling
method-local inner classes
Final variable access from class inside function
inner class instantiation from outside the the outer class
Inner classes