What is the difference between a member variable and a local variable?
Are they the same?
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.
Member variables are known as instance variables in java. Instance variables are declared in a class, but outside a method, constructor or any block.
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.
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.
A local variable is the variable you declare in a function.
A member variable is the variable you declare in a class definiton.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With