- Class variable
-
In object-oriented programming with classes, a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist.[1][2][3][4]
A class variable is the opposite of an instance variable. It is a special type of class attribute (or class property, field, or data member).
In Java, C#, and C++, class variables are declared with the keyword
static
, and may therefore be referred to as static member variables.The same dichotomy between instance and class members applies to methods ("member functions") as well; a class may have both instance methods and class methods. Again, Java, C#, and C++ use the keyword
static
to indicate that a method is a class method ("static member function").Example
struct Request { static int count; int number; Request() { number = count; // modifies the instance variable "this->number" ++count; // modifies the class variable "Request::count" } }; int Request::count = 0;
In this C++ example, the class variable
Request::count
is incremented on each call to the constructor, 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.Notes
- ^ "The Java Tutorial, Variables". http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html. Retrieved 2010-10-21.
- ^ "The Java Tutorial, Understanding Instance and Class Members". http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html. Retrieved 2010-10-21.
- ^ "The Python Language Reference, Compound Statements". http://docs.python.org/reference/compound_stmts.html#class-definitions. Retrieved 2010-10-21.
- ^ "Objective-C Runtime Reference". http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html. Retrieved 2010-10-21.
Categories:- Object-oriented programming
- Variable (computer programming)
Wikimedia Foundation. 2010.