Inclass-based,object-oriented programming,aclass variableis avariabledefined in aclassof which a single copy exists, regardless of how manyinstancesof the class exist.[1][2][3][4][5]

A class variable is not aninstance variable.It is a special type ofclass attribute(or class property,field,or data member). The same dichotomy betweeninstanceandclassmembers applies tomethods( "member functions" ) as well; a class may have bothinstance methodsandclass methods.

Static member variables and static member functions

edit

In some languages, class variables and class methods are either statically resolved, not viadynamic dispatch,or their memorystatically allocatedat compile time (once for the entire class, asstatic variables), not dynamically allocated at run time (at every instantiation of an object). In other cases, however, either or both of these are dynamic. For example, if classes can be dynamically defined (at run time), class variables of these classes are allocated dynamically when the class is defined, and in some languages class methods are also dispatched dynamically.

Thus in some languages,static member variableorstatic member functionare used synonymously with or in place of "class variable" or "class function", but these are not synonymous across languages. These terms are commonly used inJava,C#,[5]andC++,where class variables and class methods are declared with thestatickeyword,and referred to asstatic member variablesorstatic member functions.

Example

edit
structRequest{

staticintcount;
intnumber;

Requestobject(){
number=count;// modifies the instance variable "this->number"
++count;// modifies the class variable "Request::count"
}

};

intRequest::count=0;

In this C++ example, the class variableRequest::countisincrementedon each call to theconstructor,so thatRequest::countalways holds the number of Requests that have been constructed, and each new Request object is given anumberin sequential order. Sincecountis a class variable, there is only one objectRequest::count;in contrast, each Request object contains its own distinctnumberfield.

Also note that the variableRequest::countis initialized only once.

Python

edit
classDog:
vertebrate_group='mammals'# class variable

dog_1=Dog
print(dog_1.vertebrate_group)# accessing the class variable

In the above Python code, it does not provide much information as there is only class variable in the Dog class that provide the vertebrate group of dog as mammals. In instance variable, you could customize your own object (in this case, dog_1) by having one or moreinstance variablesin the Dog class.

Notes

edit
  1. ^"The Java Tutorial, Variables".Retrieved2010-10-21.
  2. ^"The Java Tutorial, Understanding Instance and Class Members".Retrieved2010-10-21.
  3. ^"The Python Language Reference, Compound Statements".Retrieved2010-10-21.
  4. ^"Objective-C Runtime Reference".Apple Developer.Retrieved1 April2018.
  5. ^ab"Class Variables in C#".Syntaxdb.Retrieved1 April2018.