Class and Instance Variable

What is the difference between a class variable and an instance variable?

Questions by chithira_s   answers by chithira_s

Showing Answers 1 - 3 of 3 Answers

ravi_1229

  • Mar 24th, 2008
 

Instance variables created  per copy.
for ex:
class A{
    private String instVariable="Hello";
    public static void main(String a[]){
       A obj1=new A();
       A obj2=new A();

    }
}

1) the above class creates two objects (obj1, obj2) for the class A
2) for each object there will be a copy of instVariable cerated in memory.
3) that means for obj1 there will be one instVariable and for obj2 there will be another instVariable.
4) i.e.,  obj1.instVariable!=obj2.instVariable
5) instance Variables are used by creating an object to that.


on the other hand,

Class Variables are also referred to static variables. Class variables  are created only once.  they can be called directly using  class name. they must be defined using static keyword.
ex:
class A{
 private staic String str="Hello World!!";
}
when we declare like this in a class the str object is instantiated and stored  in memory.
no matter how many objects you create for the
class A.
only one class variable(str) will be created in the memory and all the objects refer to that memory location.
    If you want to know how many times the class is being called , put a static variable and increment the variable in the constructor of that class.
 

for further information see :
http:// java.sun . com/docs/books/tutorial/java/javaOO/classvars . html

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions