Jump to content

Member variable: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m Minor edits
mNo edit summary
Tags: Mobile edit Mobile app edit iOS app edit
 
(38 intermediate revisions by 31 users not shown)
Line 1: Line 1:
{{Short description|Variable associated with a specific object, and accessible for all its methods}}
In [[object-oriented programming]], a '''member variable''' (sometimes called a '''member [[Field (computer science)|field]]''') is a [[variable (programming)|variable]] that is associated with a specific object, and accessible for all its [[method (computer science)|methods]] (''member functions''). In [[Class (computer science)|class]]-based languages, these are distinguished into two types: if there is only one copy of the variable shared with all instances of the class, it is called a [[class variable]] or static member variable; while if each instance of the class has its own copy of the variable, the variable is called an [[instance variable]].<ref>{{cite web | accessdate = 2011-08-12 | author = Richard G. Baldwin | date = 1999-03-10 | location = http://www.dickbaldwin.com/ | publisher = Richard G Baldwin Programming Tutorials | title = Q - What is a member variable? | quote = A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable). It must be declared within a class, but not within the body of a method of the class. | url = http://www.dickbaldwin.com/java/Java020.htm}}</ref>
In [[object-oriented programming]], a '''member variable''' (sometimes called a '''member [[Field (computer science)|field]]''') is a [[variable (programming)|variable]] that is associated with a specific [[Object (computer science)|object]], and accessible for all its [[method (computer science)|methods]] (''member functions'').


In [[class-based programming]] languages, these are distinguished into two types: ''[[class variable]]s'' (also called ''static member variables''), where only one copy of the variable is shared with all [[instance (computer science)|instance]]s of the [[Class (computer programming)|class]]; and ''[[instance variable]]s'', where each instance of the class has its own independent copy of the variable.<ref>{{cite web | accessdate = 2011-08-12 | author = Richard G. Baldwin | date = 1999-03-10 | publisher = Richard G Baldwin Programming Tutorials | title = Q - What is a member variable? | quote = A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable). It must be declared within a class, but not within the body of a method of the class. | url = http://www.dickbaldwin.com/java/Java020.htm}}</ref>
== Examples ==

== For Examples ==
=== C++ ===
=== C++ ===
<syntaxhighlight lang="cpp">
<syntaxhighlight lang="cpp">

#include <iostream>
class Foo {
class Foo {
int bar; // Member variable
int bar; // Member variable
public:
public:
void setBar (const int newBar) { bar = newBar; }
void setBar(const int newBar) {
bar = newBar;
}
};
};


Line 19: Line 24:
=== Java ===
=== Java ===
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
class Program
public class Program
{
{
static void main(final String arguments[])
public static void main(String[] args)
{
{
// This is a local variable. Its lifespan
// This is a local variable. Its lifespan
Line 29: Line 34:
}
}


class Foo
public class Foo
{
{
// This is a member variable - a new instance
/* This is a member variable - a new instance
// of this variable will be created for each
of this variable will be created for each
// new instance of Foo. The lifespan of this
new instance of Foo. The lifespan of this
// variable is equal to the lifespan of "this"
variable is equal to the lifespan of "this"
// instance of Foo
instance of Foo
*/

int bar;
int bar;
}
}
</syntaxhighlight>

=== Python ===
<syntaxhighlight lang="python">
class Foo:
def __init__(self):
self._bar = 0

@property
def bar(self):
return self._bar

@bar.setter
def bar(self, new_bar):
self._bar = new_bar

f = Foo()
f.bar = 100
print(f.bar)
</syntaxhighlight>

=== Common Lisp ===
<syntaxhighlight lang="lisp">
(defclass foo () (bar))
(defvar f (make-instance 'foo))
(setf (slot-value f 'bar) 100)
(print (slot-value f 'bar))
</syntaxhighlight>

=== Ruby ===
<syntaxhighlight lang="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 (if any)
@@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 = false)
@trained = trained
end

def has_manners?
@trained
end

end

p = Poodle.new
p.class.sheds #=> false
p.has_manners? #=> false
</syntaxhighlight>

=== PHP ===
<syntaxhighlight lang="php">
<?php

class Example
{
/**
* Example instance member variable.
*
* Member variables may be public, protected or private.
*
* @var int
*/
public int $foo;
/**
* Example static member variable.
*
* @var bool
*/
protected static int $bar;
/**
* Example constructor method.
*
* @param int $foo
*/
public function __construct(int $foo)
{
// Sets foo.
$this->foo = $foo;
}
}

// Create a new Example object.
// Set the "foo" member variable to 5.
$example = new Example(5);

// Overwrite the "foo" member variable to 10.
$example->foo = 10;

// Prints 10.
echo $example->foo;
</syntaxhighlight>

=== Lua ===
<syntaxhighlight lang="lua">
--region example
--- @class example_c
--- @field foo number Example "member variable".
local example_c = {}
local example_mt = {__index = example_c}

--- Creates an object from example.
--- @return example_c
function example_c.new(foo)
-- 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({
foo = foo
}, example_mt)
end
--endregion

-- Create an example object.
-- Set the "foo" member variable to 5.
local example = example_c.new(5)

-- Overwrite the "foo" member variable to 10.
example.foo = 10

-- Prints 10.
print(example.foo)
</syntaxhighlight>
</syntaxhighlight>


Line 43: Line 195:
* [[Global variable]]
* [[Global variable]]
* [[Local variable]]
* [[Local variable]]
* [[Property (programming)]]


== References ==
== References ==
{{Reflist|2}}
{{Reflist}}


[[Category:Object-oriented programming]]
[[Category:Object-oriented programming]]
[[Category:Variable (computer science)]]
[[Category:Variable (computer science)]]
[[Category:Articles with example Python (programming language) code]]

{{Compu-prog-stub}}

Latest revision as of 18:02, 24 August 2022

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).

In class-based programming languages, these are distinguished into two types: class variables (also called static member 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.[1]

For Examples

[edit]

C++

[edit]
class Foo {
    int bar; // Member variable
  public:
    void setBar(const int newBar) { 
      bar = newBar;
    }
};

int main () {
  Foo rect; // Local variable

  return 0;
}

Java

[edit]
public class Program
{
    public static void main(String[] args)
    {
    	// This is a local variable. Its lifespan
    	// is determined by lexical scope.
    	Foo foo;
    }
}

public class Foo
{
    /* This is a member variable - a new instance
     of this variable will be created for each 
     new instance of Foo.  The lifespan of this
     variable is equal to the lifespan of "this"
     instance of Foo
    */

    int bar;
}

Python

[edit]
class Foo:
    def __init__(self):
        self._bar = 0

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, new_bar):
        self._bar = new_bar

f = Foo()
f.bar = 100
print(f.bar)

Common Lisp

[edit]
(defclass foo () (bar))                                                         
                                                                                
(defvar f (make-instance 'foo))                                                 
(setf (slot-value f 'bar) 100)
(print (slot-value f 'bar))

Ruby

[edit]
/*
  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 (if any)
  @@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 = false)
    @trained = trained
  end

  def has_manners?
    @trained
  end

end

p = Poodle.new
p.class.sheds #=> false
p.has_manners? #=> false

PHP

[edit]
<?php

class Example
{
    /**
     * Example instance member variable.
     *
     * Member variables may be public, protected or private.
     *
     * @var int
     */
    public int $foo;
    
    /**
     * Example static member variable.
     *
     * @var bool
     */
    protected static int $bar;
    
    /**
     * Example constructor method.
     *
     * @param int $foo
     */
    public function __construct(int $foo)
    {
        // Sets foo.
        $this->foo = $foo;
    }
}

// Create a new Example object.
// Set the "foo" member variable to 5.
$example = new Example(5);

// Overwrite the "foo" member variable to 10.
$example->foo = 10;

// Prints 10.
echo $example->foo;

Lua

[edit]
--region example
--- @class example_c
--- @field foo number Example "member variable".
local example_c = {}
local example_mt = {__index = example_c}

--- Creates an object from example.
--- @return example_c
function example_c.new(foo)
  -- 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({
    foo = foo
  }, example_mt)
end
--endregion

-- Create an example object.
-- Set the "foo" member variable to 5.
local example = example_c.new(5)

-- Overwrite the "foo" member variable to 10.
example.foo = 10

-- Prints 10.
print(example.foo)

See also

[edit]

References

[edit]
  1. ^ Richard G. Baldwin (1999-03-10). "Q - What is a member variable?". Richard G Baldwin Programming Tutorials. Retrieved 2011-08-12. A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable). It must be declared within a class, but not within the body of a method of the class.