In a static method,method arg name and class variable name (static) problem
madhu gun
Greenhorn
Joined: Nov 21, 2001
Posts: 25
posted
0
In my class,there are two methods(get and set)acting on a static variable xyz.In this code get method returns null instead of 2.why cant the static variable and method arg have the same name. Ofcourse it works fine if the method arg name is changed to some other name than xyz. public static void setNoOfUsers (String xyz){//pass value "2" System.out.println("CGlobal::xyz="+xyz);--line 1 xyz= xyz; }
public static String getNoOfUsers(){ System.out.println("CGlobal::getNoOfUsers::xyz="+xyz);--line 2 return xyz; }
private static String xyz= null; Is the answer like this.If it's an instance variable , "this" will be implied/supplied by the compiler,for the left hand side variable(x=y)as this.x=y;but for a static variable "x" in x=y, will x be thought as method variable only?Pl let me know the correct answer. regards madhu [ August 12, 2002: Message edited by: madhu gun ] [ August 12, 2002: Message edited by: madhu gun ]
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
When you name an argument into a method, or declare a variable inside a method, a local variable is created. If that local variable has the same name as a static variable or a member variable the local variable HIDES the other variable. If you are in a method and you want to get at a member variable you can you the "this" keyword to indicate that. this.xyz =xyz; means "set the member variable xyz equal to the local variable xyz". Of course for static variables there is no "this" associated, however you can use the classname access syntax to get at it. MyClass.xyx = xyz; means "set static variable xyz in class MyClass equal to local variable xyz. [ August 12, 2002: Message edited by: Cindy Glass ]
"JavaRanch, where the deer and the Certified play" - David O'Meara