Member variable


In object-oriented programming, a member variable is a variable that is associated with a specific object, and accessible for all its methods.
In class-based programming languages, these are distinguished into two types: class variables, where only one copy of the variable is shared with all instances of the class; and instance variables, where each instance of the class has its own independent copy of the variable.

Examples

C++


class Foo ;
int main

Java


public class Program
public class Foo

Python


class Foo:
def __init__:
self._bar = 0
@property
def bar:
return self._bar
@bar.setter
def bar:
self._bar = new_bar
f = Foo
f.bar = 100
print

Ruby


/*
Ruby has three member variable types: class, class instance, and instance.
  • /
class Dog
# The class variable is defined within the class body with two at-signs
# and describes data about all Dogs *and* their derived Dog breeds
@@sniffs = true
end
mutt = Dog.new
mutt.class.sniffs #=> true
class Poodle < Dog
# The "class instance variable" is defined within the class body with a single at-sign
# and describes data about only the Poodle class. It makes no claim about its parent class
# or any possible subclass derived from Poodle
@sheds = false
# When a new Poodle instance is created, by default it is untrained. The 'trained' variable
# is local to the initialize method and is used to set the instance variable @trained
# An instance variable is defined within an instance method and is a member of the Poodle instance
def initialize
@trained = trained
end
def has_manners?
@trained
end
end
p = Poodle.new
p.class.sheds #=> false
p.has_manners? #=> false

PHP (7.x)


class Example
// Create a new Example object.
// Set the "foo" member variable to 5.
$example = new Example;
// Overwrite the "foo" member variable to 10.
$example->foo = 10;
// Prints 10.
print;

Lua (5.1)


--region example
--- @class example_c
--- @field foo number Example "member variable".
local example_c =
local example_mt =
--- Creates an object from example.
--- @return example_c
function example_c.new
-- The first table argument is our object's member variables.
-- In a Lua object is a metatable and its member variables are table key-value pairs.
return setmetatable
end
--endregion
-- Create an example object.
-- Set the "foo" member variable to 5.
local example = example_c.new
-- Overwrite the "foo" member variable to 10.
example.foo = 10
-- Prints 10.
print