This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

something puzzled about "static"

 
zhu weitao
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code about:


the var "maxElements" in class "Use" is declared "static",
but here ,it's used in this method "this.maxElements",
does it belong to a class not a object?

I tried it,and it did compile and run correctly

why???
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

this.maxElements = maxElements;


At the time of compilation compiler will treat this statement as
Use.maxElement.
Static variables are always class variables.
 
Ben Smither
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java allows to use a reference to an object instance to refer static variables and methods. The this in the constructor is the same as an object reference "useA" in the example as follows.
Use useA = new Use();
useA.maxElements = 100;



Originally posted by zhu weitao:
code about:


the var "maxElements" in class "Use" is declared "static",
but here ,it's used in this method "this.maxElements",
does it belong to a class not a object?

I tried it,and it did compile and run correctly

why???
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You just cannot use "this" or "super" within Static methods.
It will give a compiler error.
[ September 11, 2008: Message edited by: Nabila Mohammad ]
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Java allows to use a reference to an object instance to refer static variables and methods. The this in the constructor is the same as an object reference "useA" in the example as follows.
Use useA = new Use();
useA.maxElements = 100;

java allow us to use objects to refer to static variables and methods.
But we should not use objects references to refer to statics.....
At compilation time object references get repleces with class name.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic