This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance Variables & Class Variables

 
Angela D'souza
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to know the difference between Instance Varible and Class Variables(Static Variables)?
When We create instance of class, what is the diffference between Static Variables and Instance variables?
Thanks
Angela
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela
The quick answer is:
instance (member) variables are variables that belong to each iondiovidual instance of an object. Each instance has its own copy of the variable.
static (class) variables belong to the class itself there is only one copy of the variable no matter how many of instances of the class there are.
This can be a fairly detailed topic and you can find other resources for it:
the java tutorial is probably the place to start.
hope that helps
 
Angela D'souza
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dave,
So,If I have class bicycle:
In bicycle, if i declare Static Variable currentGear = 45.If I create 2 instance of this class, bicycle a, bicycle b and in a if can I change the the value of currentGear? If yes, then the value of currentGear in b and class itself will be changed or not???
same question for instance variable???
BTW, I read the java tutorial, still I have above confusion.
I would appreciate answer(If it is by simple example)
Thanks
Angela
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Angela D'souza:
So,If I have class bicycle:
In bicycle, if i declare Static Variable currentGear = 45.If I create 2 instance of this class, bicycle a, bicycle b and in a if can I change the the value of currentGear? If yes, then the value of currentGear in b and class itself will be changed or not???
same question for instance variable???




Notice the output after each change. Now remove the "static" modifier from currentGear, and see how the output differs. (Note: You will need to comment out this line:
System.out.println( "Bicycle.currentGear: " + Bicycle.currentGear );
or it won't compile.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic