• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is accessible to a class defined in a method

 
Murad Iqbal
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read and understood till now that only the arguments, with final keyword, passed to a method are accessible to a class defined in that method. However, I saw in a program that the class variables in which that method exist, are also accessible by the class defined within a method. Please someone be kind enough to tell what is the complete concept?

Thanks,
Murad.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All variables have a "scope," which you should find out about in your Java books or look where a variable is called "visible" in this part of the Java tutorial. Scope does not vary for final variables, but as you imply, local variables and parameters used by an inner class have to be declared final.


Not the official way to look at it:- The scope of a variable is from the { last before it is declared until just before the } which matches it. If you look on a field as a variable then the { before is the beginning of the class and the } after is the end of the class . For a parameter, its scope is the whole of its method.

Inner classes in a method have access to:-
  • Fields (public protected [package-private] and private). They don't need to be final.
  • Local variables in their surrounding method, but they have to be final.
  • Parameters for that method, again final.

  • [ March 17, 2007: Message edited by: Campbell Ritchie ]
     
    Murad Iqbal
    Ranch Hand
    Posts: 90
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks Camp, that was good explanation.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic