Member variable

Last updated

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).

Contents

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

C++

classFoo{intbar;// Member variablepublic:voidsetBar(constintnewBar){bar=newBar;}};intmain(){Foorect;// Local variablereturn0;}

Java

publicclassProgram{publicstaticvoidmain(String[]args){// This is a local variable. Its lifespan// is determined by lexical scope.Foofoo;}}publicclassFoo{/* 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    */intbar;}

Python

classFoo:def__init__(self):self._bar=0@propertydefbar(self):returnself._bar@bar.setterdefbar(self,new_bar):self._bar=new_barf=Foo()f.bar=100print(f.bar)

Common Lisp

(defclassfoo()(bar))(defvarf(make-instance'foo))(setf(slot-valuef'bar)100)(print(slot-valuef'bar))

Ruby

/*  Ruby has three member variable types: class, class instance, and instance.*/classDog# 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=trueendmutt=Dog.newmutt.class.sniffs#=> trueclassPoodle<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 instancedefinitialize(trained=false)@trained=trainedenddefhas_manners?@trainedendendp=Poodle.newp.class.sheds#=> falsep.has_manners?#=> false

PHP

<?phpclassExample{/**     * Example instance member variable.     *     * Member variables may be public, protected or private.     *     * @var int     */publicint$foo;/**     * Example static member variable.     *     * @var bool     */protectedstaticint$bar;/**     * Example constructor method.     *     * @param int $foo     */publicfunction__construct(int$foo){// Sets foo.$this->foo=$foo;}}// Create a new Example object.// Set the "foo" member variable to 5.$example=newExample(5);// Overwrite the "foo" member variable to 10.$example->foo=10;// Prints 10.echo$example->foo;

Lua

--region example--- @class example_c--- @field foo number Example "member variable".localexample_c={}localexample_mt={__index=example_c}--- Creates an object from example.--- @return example_cfunctionexample_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.returnsetmetatable({foo=foo},example_mt)end--endregion-- Create an example object.-- Set the "foo" member variable to 5.localexample=example_c.new(5)-- Overwrite the "foo" member variable to 10.example.foo=10-- Prints 10.print(example.foo)

See also

Related Research Articles

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

In object-oriented programming (OOP), the object lifetime of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementations of a given language, and lifetime of a particular object may vary from one run of the program to another.

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. Function objects are often called functors.

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed identifier or address.

In class-based, object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Java syntax Set of rules defining correctly structured programs

The syntax of Java refers to the set of rules defining how a Java program is written and interpreted.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

The uniform access principle of computer programming was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation". This principle applies generally to the syntax of object-oriented programming languages. In simpler form, it states that there should be no syntactical difference between working with an attribute, pre-computed property, or method/query of an object.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity of which the currently running code is a part. The entity referred to by these keywords thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, they can disambiguate variables and functions with the same name.

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted. The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field and a method. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for data validation, active updating, or implementation of what may be called "read-only fields".

In computer programming, scope is an enclosing context where values and expressions are associated. The scope resolution operator helps to identify and specify the context to which an identifier refers, particularly by specifying a namespace. The specific uses vary across different programming languages with the notions of scoping. In many languages, the scope resolution operator is written ::.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system.

In object-oriented programming, forwarding means that using a member of an object results in actually using the corresponding member of a different object: the use is forwarded to another object. Forwarding is used in a number of design patterns, where some members are forwarded to another object, while others are handled by the directly used object. The forwarding object is frequently called a wrapper object, and explicit forwarding members are called wrapper functions.

References

  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.