Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a member variable and a local variable?

Tags:

variables

What is the difference between a member variable and a local variable?

Are they the same?

like image 245
Chin Avatar asked Jul 24 '09 13:07

Chin


People also ask

What is meant by member variable?

Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.

What are member variables called?

Member variables are known as instance variables in java. Instance variables are declared in a class, but outside a method, constructor or any block.

What is the difference between a local variable and a field?

A local variable is defined within the scope of a block. It cannot be used outside of that block. I cannot use local outside of that if block. An instance field, or field, is a variable that's bound to the object itself.

What is the difference between member variables and static variables?

An instance variable is a property of an instance. A static variable is created only once when the classloader loads the class. An instance variable is created everytime an instance is created. A static variable is used when you want to store a value that represents all the instances like count, sum, average etc.


2 Answers

A local variable is the variable you declare in a function.

A member variable is the variable you declare in a class definiton.

like image 180
ufukgun Avatar answered Oct 05 '22 02:10

ufukgun


A member variable is a member of a type and belongs to that type's state. A local variable is not a member of a type and represents local storage rather than the state of an instance of a given type.

This is all very abstract, however. Here is a C# example:

class Program {     static void Main()     {         // This is a local variable. Its lifespan         // is determined by lexical scope.         Foo foo;     } }  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; } 
like image 31
Andrew Hare Avatar answered Oct 05 '22 02:10

Andrew Hare