This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
A class variable (for example: static int var1) is shared between all instances (objects) of the class. If a method updates a class variable all the other objects of the class will see the the one changed value.
An instance variable (for example:int var2) is unique to each instance of the class. If an object updates its instance variable it does not affect the values of the instance variable in the other objects of the class.
Please, in future, consider asking such basic questions in our Java In General (Beginner) forum. Thanks -Barry
1)Class Variables:- these are variables marked as static,they are binded to the class itself thats why they are called class variables,these variables can be accessed by two method classname.variable,object.variable,but for all of them there exist only a single instance of class variable,moreover these variables are automatically initialized at class loadtime and implicitly given a default value of that primitive. here is code to help you out and will clear our doubts
Results into 0 15 10
2)Instance Variables:- They are binded to the particular instance of class itself thats why they are called instance variables,these variables can be accessed by object.variable,for all of instances there exist a different instance variable,these variables are automatically initialized at object creation and implicitly given a default value of that primitive. here is code to help you out and will clear our doubts
which results into 0 15 [ September 17, 2005: Message edited by: anand phulwani ]
Thanks and Regards, Anand
SCJP 5.0 310-055 73%, SCWCD 1.4 310-081 78%, IBM DB2 9 Fundamentals 000-730 62%
Joined: Aug 03, 2002
Anand's post reminded me of something else. It is strongly recommended not to refer to a class variable through an object instance. That is, as obj.myClassVariable. It is recommended that you either use myClassVariable (in the defining class) or MyClass.myClassVariable (where MyClass is the class where myClassVariable is defined). The whole point of class variables is that you do not need an instance of MyClass to be able to reference them.
(Strange but true: you can, but should not, use ((MyClass)null).myClassVariable or MyClass ref = null; ref.myClassVariable to access a class variable )
Joined: Sep 10, 2005
Dear MR Barry,
With refernce to your above post,i would like to know what should we do in the exam when a question regarding this that a class variable is accessed by an object reference comes.
what i think is although sun advices we shouldnt do this ,but related to exam,i think we have to see what runs and what not,hope i am right and you would agree with me.