• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing Global Variable...  RSS feed

 
lee chan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi below is my class...



OUTPUT:
a... in b....12
a... in c....0

Please help me out how to get the same value of a which is in method b into method c
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's going on there is "variable hiding".

In method b(), you've got access to two separate variables a:
- one that's declared as a static member of the class
- one that's declared as an argument in of the method

The second takes precendence, so the variable that's been changed is not the one that you can access from method c()

How you'd fix it? Avoid using the same variable name for different variables. Or explicitly refer to Test.a if that's what you want.
 
N Sahni
Ranch Hand
Posts: 55
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just change the method signature of b as

The value of a which you are trying to update in method b is getting reflected in local copy of method.

Or, may be you can access static a as Test.a which is a recommended way of accessing static variables.
 
lee chan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:What's going on there is "variable hiding".

In method b(), you've got access to two separate variables a:
- one that's declared as a static member of the class
- one that's declared as an argument in of the method

The second takes precendence, so the variable that's been changed is not the one that you can access from method c()

How you'd fix it? Avoid using the same variable name for different variables. Or explicitly refer to Test.a if that's what you want.


Thank you.

After changing the code in method b() from
a = 12; to Test.a = 12;
am able to print the value of a as in method b() into method c();
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!