Java Forum / General / September 2007
Usage of Static variable name in static context
Vikram Kalra - 03 Sep 2007 12:40 GMT Hi All
I am new to this group and to java too.
I have a question regarding variable name hiding for static variables in a static context. Here is the sample code:
class RangeClass{ static int i;
public static void main(String args[]){ setI(10); int i = getI();
System.out.println(i); }
static void setI(int i){ this.i = i; }
static int getI(){ return i; } }
In the code above, you can see method setI, which takes an integer with name 'i' as an arguement which is same as the name of the static variable declared in the class.
Now can anyone tell me how can i refer to the static variable 'i' in method setI keeping the same name of the arguement?
Regards Vikram
Vikram Kalra - 03 Sep 2007 12:52 GMT Oops ! A small change in the code is needed to compile properly, as i am using 'this' in a static context which doesn't compile. Thus kindly suggest me some solution for the same question i asked above ......
> Hi All > [quoted text clipped - 31 lines] > Regards > Vikram Vikram Kalra - 03 Sep 2007 12:52 GMT Oops ! A small change in the code is needed to compile properly, as i am using 'this' in a static context which doesn't compile. Thus kindly suggest me some solution for the same question i asked above ......
> Hi All > [quoted text clipped - 31 lines] > Regards > Vikram Andreas Leitgeb - 03 Sep 2007 13:02 GMT > Oops ! A small change in the code is needed to compile properly, as i > am using 'this' in a static context which doesn't compile. > Thus kindly suggest me some solution for the same question i asked > above ......
>> class RangeClass{ [...]
>> static void setI(int i){ >> this.i = i; >> } Try: RangeClass.i
Chris Dollin - 03 Sep 2007 13:08 GMT > I have a question regarding variable name hiding for static variables > in a static context. Here is the sample code: [quoted text clipped - 24 lines] > Now can anyone tell me how can i refer to the static variable 'i' in > method setI keeping the same name of the arguement? Why would you want to?
Rename the variables to something sensible and the problem evaporates.
 Signature Chris "sublime" Dollin
Hewlett-Packard Limited registered office: Cain Road, Bracknell, registered no: 690597 England Berks RG12 1HN
Nigel Wade - 03 Sep 2007 15:00 GMT > Hi All > [quoted text clipped - 31 lines] > Regards > Vikram You can refer to a static (class) member by prefixing it with the class name:
static void setI(int i){ RangeClass.i = i; }
It's best not to use tabs in code. Not all news readers handle them in the same way. Tabbed code can sometimes be very hard to decipher.
 Signature Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw@ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Lew - 03 Sep 2007 15:37 GMT > It's best not to use tabs in code [that's posted to Usenet]. > Not all news readers handle them in the sameway. > Tabbed code can sometimes be very hard to decipher. As can top-posting.
Several people have pointed out that the way to refer to a static variable is by the syntax Classname.staticVariable
Chris Dollin also pointed out:
> Rename the variables to something sensible and the problem evaporates. This is a very important principle. This answer is not a dodge or hack to avoid having to say "RangeClass.i". Rather, it's a signpost to good, solid, maintainable, professional code. Variable names, especially for class and instance variables, should be self-descriptive. "i" is far too terse for a good variable name. What is "i"? A range limit? A unique id? A counter? Something else entirely?
Another dodge for setters is always to name the method argument "value".
public void setLimit( int value ) { limit = value; }
Works great for static or instance methods.
Check out these resources for new Java developers: <http://java.sun.com/docs/books/tutorial/index.html> <http://www.mindprod.com/jgloss/gettingstarted.html>
In general, <http://www.mindprod.com/> has a ton of great education in it.
 Signature Lew
Daniel Pitts - 03 Sep 2007 17:10 GMT > > It's best not to use tabs in code [that's posted to Usenet]. > > Not all news readers handle them in the sameway. [quoted text clipped - 34 lines] > -- > Lew I would even go as far as to say that if you make it into a non-static member, you would be better off.
class RangeClass { private int lower;
public void setLower(int lower) { this.lower = lower; } //etc... so forth }
If you need to only have one instance of lower shared between all objects, then look into the singleton pattern. Although, I personally try to avoid the singleton pattern and use dependency injection where possible.
Nigel Wade - 03 Sep 2007 17:14 GMT >> It's best not to use tabs in code [that's posted to Usenet]. >> Not all news readers handle them in the sameway. >> Tabbed code can sometimes be very hard to decipher. > > As can top-posting. To what are you referring? I didn't top post.
If you have something to point out kindly include the actual posted message, not your snipped version.
> Several people have pointed out that the way to refer to a static variable is > by the syntax > Classname.staticVariable Not when I posted my answer, unless the original post had been multi-posted and those responses where in a different NG. Of course, it's entirely possible that my news server hasn't yet received answers which have already appeared on your news server. Usenet isn't instant messaging...
 Signature Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw@ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Lew - 03 Sep 2007 17:24 GMT > To what are you referring? I didn't top post. Sorry for the confusion. I was referring to the OP's top-posting.
> If you have something to point out kindly include the actual posted message, not > your snipped version. Good point. I apologize.
Lew:
>> Several people have pointed out that the way to refer to a static variable is >> by the syntax >> Classname.staticVariable Nigel Wade:
> Not when I posted my answer, unless the original post had been multi-posted and Again, my fault. I was attempting to summarize for the OP what two (not "several") people said, as a lead-in to my comments.
Let me clarify, if I may. I wanted to point out for the OP and other listeners some sources of information and additional comments about the excellent advice already rendered by Nigel and others. I apologize for engendering misunderstanding.
 Signature Lew
Roedy Green - 03 Sep 2007 20:21 GMT >class RangeClass{ > static int i; [quoted text clipped - 14 lines] > } >} you can't say this.i because that would refer to an instance variable. To get at static i you would have to say RangeClass.i There is no this-like keyword for "static of this class".
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Wayne - 05 Sep 2007 13:37 GMT >> class RangeClass{ >> static int i; [quoted text clipped - 18 lines] > To get at static i you would have to say RangeClass.i > There is no this-like keyword for "static of this class". This is not quite as I understand it. The problem with the above is that the "this" keyword can't be used here; "this" is implicitly declared only in instance methods and not in static ones.
You *can* refer to a static variable using "this", from an instance method. "this" refers to all class members in scope whether static or instance:
class TestStaticThis { static int i;
public static void main ( String [] args ) { TestStaticThis me = new TestStaticThis(); me.setI( 2 ); me.showI(); }
void setI ( int i ) { this.i = i; }
void showI () { System.out.println( "this.i = " + this.i ); } }
[From your previous posts I know you knew that, but it didn't seem clear here.]
Explaining static is a perennial problem, there just doesn't seem to be a good way to explain the concept clearly.
-Wayne
Lew - 05 Sep 2007 14:51 GMT >>> class RangeClass{ >>> static int i; [quoted text clipped - 21 lines] > that the "this" keyword can't be used here; "this" is implicitly > declared only in instance methods and not in static ones. That's what Roedy said.
 Signature Lew
Nigel Wade - 05 Sep 2007 16:29 GMT >>>> class RangeClass{ >>>> static int i; [quoted text clipped - 23 lines] > > That's what Roedy said. Roedy stated that you couldn't use this.i because it refers to an instance variable. "this" refers to an instance of the class, but "this.i" doesn't necessarily reference a member variable i. It is perfectly permissible to reference a class variable via the specifier "this". But not in a static context, because there is no "this" just as there are no instance variables in the static context.
So it could be used in a non-static method:
public void setStaticI(int i) { this.i = i; }
but not in the method "static setI(int i)" because there would be no "this" in the static context. But not because this.i refers to an instance variable - in the method setStaticI() above this.i refers to the class variable i.
If you see what I mean...
 Signature Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw@ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Roedy Green - 06 Sep 2007 05:12 GMT >It is perfectly permissible to >reference a class variable via the specifier "this". Technically it is allowed, but it is consider poor form since it confuses the heck out of people reading your code, making a static method look like an instance one. If you run a "lint" program on your Java, e.g. IntelliJ Inspector, it will smack your wrist for doing that.
If a newbie reads your code they will be lead down the garden path to think that this.x follows the RUN-TIME type of this rather than the COMPILE-TIME type and magically selects the static method based on the run-type type. When do compile time and run time type for this differ? When a constructor calls a superclass constructor, for one.
In teaching mode, I assert that this.staticmethod is wrong.
It is much like teaching naming conventions. In theory you can violate them, but only an a.shole would without very good reason.
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Nigel Wade - 06 Sep 2007 14:09 GMT >>It is perfectly permissible to >>reference a class variable via the specifier "this". [quoted text clipped - 4 lines] > Java, e.g. IntelliJ Inspector, it will smack your wrist for doing > that. But you didn't say it was poor form. You didn't say it was confusing. You stated that it referred to an instance variable, which is incorrect.
> If a newbie reads your code they will be lead down the garden path to > think that this.x follows the RUN-TIME type of this rather than the [quoted text clipped - 6 lines] > It is much like teaching naming conventions. In theory you can violate > them, but only an a.shole would without very good reason. It's not like that at all. Teaching good practice and convetions is one thing. Teaching things which are blatantly incorrect (even with the best of intentions) is something else entirely.
 Signature Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw@ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Lew - 06 Sep 2007 14:57 GMT >>> It is perfectly permissible to >>> reference a class variable via the specifier "this". But not from a static method, since "this" refers to an instance, thus cannot be used in a static context.
So when Roedy said
> you can't say this.i because that would refer to an instance variable. he was exactly correct, given that the conversation was about static methods.
JLS: <http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.3>
> The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.
 Signature Lew
Nigel Wade - 07 Sep 2007 09:51 GMT >>>> It is perfectly permissible to >>>> reference a class variable via the specifier "this". > > But not from a static method, since "this" refers to an instance, thus cannot > be used in a static context. I know. It was unstated because I felt it was unnecessary to state the bleedin' obvious. The compiler will tell you that you can't do it.
> So when Roedy said >> you can't say this.i because that would refer to an instance variable. > he was exactly correct, given that the conversation was about static methods. He stated that this.i refers to an instance variable. In a static method there is no "this" so it can't refer to anything. In a non-static context it would refer to the static member "i". Thus, his statement was incorrect in either context.
 Signature Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw@ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Roedy Green - 07 Sep 2007 04:47 GMT >But you didn't say it was poor form. You didn't say it was confusing. You stated >that it referred to an instance variable, which is incorrect. The form this.x is used to refer to instance variables. a.sholes use it to refer to static variables.
You can drive your car at 130 mph, but that is not what they teach in driver ed.
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Wayne - 07 Sep 2007 00:52 GMT > ... > Technically it is allowed, but it is consider poor form since it [quoted text clipped - 13 lines] > It is much like teaching naming conventions. In theory you can violate > them, but only an a.shole would without very good reason. I agree completely, and I only teach that in passing, as an aid to understanding code errors. My students never seem to have learned scope and lifetime concepts in any pre-requisite class, so I teach it. Understanding "static" seems very hard for my students, I guess I need a better way to teach that, I haven't found one yet that is clear to my students (Newbies all).
Frankly I prefer the C++ convention, of className::var (for static) and this.var (for instance) var, but Java doesn't have the "::" (scope resolution) operator. I have noticed Eclipse shows static identifiers in italic font, that helps a little I guess. If you use Eclipse anyway.
Teaching code should show best practices (except on exams :-). But you also need to be technically accurate even for the confusing bits, or the students will have a hard time debugging, passing Sun Java Certification exams, etc.
If someone has found a great way to teach Java scoping / static rules to newbies, I'd love to steal your method! Please share as this thread seems a good place to do so.
-Wayne
Stefan Ram - 07 Sep 2007 01:59 GMT >My students never seem to have learned scope and lifetime >concepts in any pre-requisite class, so I teach it. >Understanding "static" seems very hard for my students, I guess >I need a better way to teach that, I haven't found one yet that >is clear to my students (Newbies all). The keyword »static« does not have a single meaning.
For example, in
class A { static int x = 0; static void f(){} static class B{} }
different wording might be needed to explain the meaning of each »static«.
>Frankly I prefer the C++ convention, of className::var (for static) >and this.var (for instance) var, Possibly, in C++, it would be »this->var«.
Reference were introduced to C++ after »this«, so »this« is not a reference, but a pointer.
>If someone has found a great way to teach Java scoping / >static rules to newbies, I'd love to steal your method! Usually, lifetime and dynamic concepts (like recursion) are more difficult to grasp than static scoping.
Roedy Green - 07 Sep 2007 05:04 GMT >{ static int x = 0; > static void f(){} > static class B{} } > > different wording might be needed to explain the meaning of > each »static« The name was inherited from C where it had yet a different meaning -- allocation worked out at compile/link time.
If Java were being reinvented perhaps a more meaningful keyword should be used: e.g.
perclass, shared, common, once.
It might also be nice to have an explicit "instance" keyword so that methods would be neatly categorised into "instance" and "common".
Perhaps you could recycle two pronouns this(object) and that(class) or here(class).
for static inner classes, how about "independent" or "free".
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Ben Phillips - 07 Sep 2007 09:09 GMT > class A > { static int x = 0; [quoted text clipped - 3 lines] > different wording might be needed to explain the meaning of > each »static«. Not really. In all three cases, static means the thing is associated with the class A but not with specific instances of A.
In the int's case lack of "static" would mean that each instance has a separate value for x; in the method's case that the method must be invoked on a specific instance of A and acts on that instance; and in the nested class's case that an instance of the nested class is associated with a specific instance of A (making it an "inner" class).
So the details of how it's associated with a specific instance vary, but they all have in common that they are associated with a specific instance.
Static, on the other hand, just means none of them are associated with a specific instance of A. Instances of B aren't; f is basically a function rather than a method; x is a global; all are scoped by A (and f and methods of B can see private members of A).
It's more that non-static is a bit different in each case, really. :)
> Usually, lifetime and dynamic concepts (like recursion) > are more difficult to grasp than static scoping. The simple meaning of static scoping is basically "there's only one". Although with the nested class B above, there's technically only one whether or not it's static, it can be thought of as having a "copy" for each instance of A if it's not in a certain sense. You could conceptualize this as an anonymous subclass, so that they are all assignable to any reference of type B regardless of which instance of A they are attached to. Although it's not implemented that way under the hood, I don't think, and reflection will only ever show you a single class B and no subclasses you don't explicitly make (barring arcane and unusual multiple-classloader use anyway).
But basically that's it. All are associated with the class A as regards lexical scoping and having access to A's private parts. The non-statics are used in connection with instances of A and may vary in behavior modulo which instance. The statics are not and may not, and referencing them through specific instances just aliases them. When used they are associated only with the class A and not any specific instance, however they were accessed. Of course this means that the static method f() cannot be polymorphic either, since only an instance could have a more specific run-time type, and f() (even when accessed via an instance of A, a.f()) when used does not behave in a way associated with a specific instance (that might have been of a subclass of A).
In practise, the subtleties (particularly f()'s non-polymorphic nature and the nested/inner class behaviors) make it necessary to give details specific to the cases of methods and nested classes. But it's really the non-static ones that have the exceptional behavior -- usage only in association with a specific instance of A, polymorphism in the case of methods, etc.
Roedy Green - 07 Sep 2007 04:51 GMT >Teaching code should show best practices (except on exams :-). But >you also need to be technically accurate even for the confusing bits, >or the students will have a hard time debugging, passing Sun Java >Certification exams, etc. My intent is to get people writing good code, not passing exams.
I remember an exam years ago in COBOL about the ID division. I thought to myself, if you get that right you should get negative points. Any sensible programmer just cuts and pastes it. Only a time-wasting nit picker would know all those fields in detail by memory.
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|