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
editIn 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 thestatic
keyword,and referred to asstatic member variablesorstatic member functions.
Example
editC++
editstructRequest{
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::count
isincrementedon each call to theconstructor,so thatRequest::count
always holds the number of Requests that have been constructed, and each new Request object is given anumber
in sequential order. Sincecount
is a class variable, there is only one objectRequest::count
;in contrast, each Request object contains its own distinctnumber
field.
Also note that the variableRequest::count
is initialized only once.
Python
editclassDog:
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- ^"The Java Tutorial, Variables".Retrieved2010-10-21.
- ^"The Java Tutorial, Understanding Instance and Class Members".Retrieved2010-10-21.
- ^"The Python Language Reference, Compound Statements".Retrieved2010-10-21.
- ^"Objective-C Runtime Reference".Apple Developer.Retrieved1 April2018.
- ^ab"Class Variables in C#".Syntaxdb.Retrieved1 April2018.