Usage of Static variable name in static context

V

Vikram Kalra

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
 
V

Vikram Kalra

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 ......
 
V

Vikram Kalra

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 ......
 
A

Andreas Leitgeb

Vikram Kalra said:
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
 
C

Chris Dollin

Vikram said:
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?

Why would you want to?

Rename the variables to something sensible and the problem evaporates.
 
N

Nigel Wade

Vikram said:
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

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.
 
L

Lew

Nigel said:
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.
 
D

Daniel Pitts

Nigel said:
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.

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.
 
N

Nigel Wade

Lew said:
Nigel said:
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...
 
L

Lew

Nigel said:
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:
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.
 
R

Roedy Green

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;
}
}

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".
 
W

Wayne

Roedy said:
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;
}
}

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".

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
 
L

Lew

Wayne said:
Roedy said:
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;
}
}
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".

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.

That's what Roedy said.
 
N

Nigel Wade

Lew said:
Wayne said:
Roedy said:
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;
}
}
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".

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.

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...
 
R

Roedy Green

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 asshole would without very good reason.
 
N

Nigel Wade

Roedy said:
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.

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
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 asshole 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.
 
L

Lew

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:
 
W

Wayne

Roedy said:
...
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 asshole 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
 
S

Stefan Ram

Wayne said:
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.
 
R

Roedy Green

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.
Assholes 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top