• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hidden final variable

 
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please explain how to refer to local final var if its been shadowed in inner class?

class outer {
void keepval(final int i){
class inner extends outer {
int i;
//How can I refer to the outer int i declared as final?
}
}
public static void main(String[] args) {
}
}
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Easy. Don't write code that looks like that! The way that you have written that code, you cannot refer to the argument final int i that was passed into the the method keepval from inside of the method-local inner class. From inside the inner class, you will always get the method-local inner class version of i.

I can't think of a single reason why you might ever need to define a variable inside of a method-local inner class that has the same name as a variable in the method. You are writing the inner class and can choose any variable names that you want. That makes it quite easy to avoid these kinds of naming collisions.

If you are trying to see how reference a class variable that is shadowed by the method-local inner class, then you use outerclassname.this.variablename

 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think there is no way to access the final variable of a method if it has been shadowed in a local inner class.

But what is the reason behind it, I have not been able to understand.

Kaps
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use a copy of i as a workaround:


But why shadow something you need to access in the first place?
reply
    Bookmark Topic Watch Topic
  • New Topic