Thursday, April 18, 2013

Class variable Vs Instance variable in java


-->
both variables are defined inside the class and outside to any method. Therefore both of these variables are in the class scope.

Instance variable
instance variable belongs to an instance of a class. Each instance of the class maintain its own copy of the instance variable(s). Therefore the changes or operations that are done with an instance variable will only be reflected in that instance variable. (no other instance variables are affected)

here is an example for the instance variable.

class sampleClass{

    int count;
}


Class variable
class variables are known as static member variables. Class variable is common to the all instances of the class. In other words, one class variable will be shared with all instances of the class. Class variables are modified with static modifier.

Here is an example for the class variable.

Class sampleClass{
   
    static int count;
}

instance variable and class variable.
Each object(instance) in the class has its own copy of instance variables. But every instances(objects) in the class will be shared one copy of class variables. Therefore the changes that are done for the instance variables will only be visible to that particular instance. But the changes that are done for class variables will be visible to all the instances of that class. This is because the class variables are shared among all instances of the class. Both class variable and member variables have been identified as a member variable of a class.


Hope this will helpful for you!

Regards
Chathuranga Tennakoon