What is the difference between a member variable and a local variable?
Are they the same?
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;
}
There are two kinds of member variable: instance and static.
An instance variable lasts as long as the instance of the class. There will be one copy of it per instance.
A static variable lasts as long as the class. There is one copy of it for the entire class.
A local variable is declared in a method and only lasts until the method returns:
public class Example {
private int _instanceVariable = 1;
private static int _staticvariable = 2;
public void Method() {
int localVariable = 3;
}
}
// Somewhere else
Example e = new Example();
// e._instanceVariable will be 1
// e._staticVariable will be 2
// localVariable does not exist
e.Method(); // While executing, localVariable exists
// Afterwards, it's gone
public class Foo
{
private int _FooInt; // I am a member variable
public void Bar()
{
int barInt; // I am a local variable
//Bar() can see barInt and _FooInt
}
public void Baz()
{
//Baz() can only see _FooInt
}
}
A local variable is the variable you declare in a function.Its lifespan is on that Function only.
A member variable is the variable you declare in a class definition.Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.
Variables declared within a method are "local variables"
Variables declared within the class not within any methods are "member variables"(global variables).
Variables declared within the class not within any methods and defined as static are "class variables".
A member variable belongs to an object... something which has state. A local variable just belongs to the symbol table of whatever scope you are in. However, they will be represented in memory much the same as the computer has no notion of a class... it just sees bits which represent instructions. Local variables and member variables can both be on the stack or heap.
Related
When an anonymous object is public, it is simply implemented as an object return, but when it is private, it is returned as a type-cast object. look at the Kotlin code below.
private fun foo() = object {
val x: String = "x"
}
fun bar() = object {
val x: String = "x"
}
When this code is decompiled into Java, it changes like this:
private static final <undefinedtype> foo() {
return (<undefinedtype>)(new Object() {
#NotNull
private final String x = "x";
#NotNull
public final String getX() {
return this.x;
}
});
}
#NotNull
public static final Object bar() {
return new Object() {
#NotNull
private final String x = "x";
#NotNull
public final String getX() {
return this.x;
}
};
}
Therefore, when you try to use the code, only the private anonymous object can access x.
So, why do each access modifiers have different implementations?
That is how language defines the semantics of anonymous objects.
Type of an anonymous object is only usable in the declaring scope, when you use public modifier, anonymous object escapes the current scope and is cast to Any (implicit super type). since Any doesn't have any property x, you can't access it.
on the other hand when you use private modifier you make sure that it doesn't escape the current scope.
From the Kotlin language specification
The main difference between a regular object declaration and an
anonymous object is its type. The type of an anonymous object is a
special kind of type which is usable (and visible) only in the scope
where it is declared. It is similar to a type of a regular object
declaration, but, as it cannot be used outside the declaring scope,
has some interesting effects.
When a value of an anonymous object type escapes current scope:
If the type has only one declared supertype, it is implicitly downcasted to this declared supertype;
If the type has several declared supertypes, there must be an implicit or explicit cast to any suitable type visible outside the
scope, otherwise it is a compile-time error.
Note: in this context “escaping current scope” is performed
immediately if the corresponding value is declared as a non-private
global or classifier-scope property, as those are parts of an
externally accessible interface.
What is the difference between a member variable or field and a global variable?Is the concept same ?
A member variable is declared within the scope of a class. Unless it’s static, there will be a different copy of the variable for every object of that class.
A global variable is declared outside the scope of any class and can be used from any function. There’s only one copy of it in the program.
Note that mainstream object-oriented languages distinguish between a global variable (which is declared outside the scope of any class or function) and a static local variable or class member. However, all the problems with global variables apply equally to mutable public data members that are accessible from anywhere in the program. For most purposes, you can think of these as the same thing.
Example Code
#include <iostream>
using std::cout;
using std::endl;
const int global_var = 1; // The definition of the global variable.
struct example_t {
public:
static int static_member_var; // A static member variable.
const static int const_static_member_var; // These are just declarations.
int member_var; // A non-static member variable.
// Every object of this type will have its own member_var, while all
// objects of this type will share their static members.
};
int example_t::static_member_var = 0;
const int example_t::const_static_member_var = global_var;
// We can use global_var here. Both of these exist only once in the
// program, and must have one definition. Outside the scope where we
// declared these, we must give their scope to refer to them.
int main(void)
{
example_t a, b; // Two different example_t structs.
a.member_var = 2;
b.member_var = 3; // These are different.
a.static_member_var = 5;
// This is another way to refer to it. Because b has the same variable, it
// changes it for both.
// We can use global_var from main(), too.
cout << "global_var is " << global_var
<< ", example_t::const_static_member_var is " << example_t::const_static_member_var
<< ", b.static_member_var is " << b.static_member_var
<< ", a.member_var is " << a.member_var
<< " and b.member_var is " << b.member_var
<< "." << endl;
return 0;
}
Global variables are any variables defined outside functions scope, they can be accessed anywhere in the program if they were defined outside of class scope, or they can only be accessed inside a class if they were defined inside the class's scope.
Local variables are any variables defined inside a function scope, they can only be accessed by that one function they were defined in.
Member variables are variables that are associated with a specific object of a class, they can only be declared inside a class's scope.
All member variables are global variables, but not all global variables are member variables.
Field is another term to describe variable. Similar to how method is another term to describe function, i.e. they mean the same thing, at least in Java :)
const int a = 0 // global variable, can be accessed from anywhere in the program
class Example {
int b; // member variable, also a global variable, can only be accessed inside this class
int fun () {
Foo c; // local variable, can only be accessed inside this method
return 0;
}
}
I want to change the global variable in a function where a local variable of same is already present.
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int x)
{
x=7; //here i want that this statement assigns the value 7 to the global x
}
Just qualify it with this. It's a pretty common pattern, particularly for constructors:
public class Player
{
private readonly string name;
public Player(string name)
{
this.name = name;
}
}
While I view it as acceptable if your parameter really is meant to be a new value for the field (potentially in a method which creates a new instance based on the current one and the new value for the single field, for example), I would try to avoid it in general, just from a readability perspective. Of course, the names of your private fields are an implementation detail, but when reading the code for the method, it's confusing to have two different concepts represented by the same variable name.
Rename the local parameter value.
Like Yuriy Vikulov said.
this.x for non-static variables
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int lx)
{
x=7; //if you want 7
x=lx; //if you want the paramValue
}
this.x for non-static classes
NameClass.x for static variables
I have noticed a situation where there is a class (say: ClassA) with variable declarations and various methods. And in another class (say: Class B), there is a method(MethodofClassB()) with the return type of the method as ClassA.
so it is like:
Class A
{
variable i,j;
public int MethodA()
{
//some operation
}
}
Class B
{
variable x,y;
public static A MethodB()
{
//some operation
return obj;
}
}
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
please help me understand this with a small example
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
Depends on what the method does, which isn't illustrated in this example. If the result of the operation is an instance of A then it stands to reason that it would return an instance of A, whatever A is.
For example, if A is a Car and B is a CarFactory then the method is likely producing a new Car. So it would return a Car that's been produced.
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
public allows it to be accessed by other objects. static means it's not associated with a particular instance of B. Both are subjective based, again, on the purpose of the method (which isn't defined in the example). Being static, it can be called as such:
var newInstance = B.MethodB();
If it wasn't static then an instance of B would be required:
var objectB = new B();
var newInstance = objectB.MethodB();
There are more and more implications here, including things like memory/resource usage and thread safety. All stemming from the purpose and business logic meaning of what B is and what MethodB does.
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
It would be an instance of A. Similar to creating an instance here:
var objectA = new A();
This method also creates (or in some way gets) an instance:
var objectA = B.MethodB();
Without knowing more about what A is, what its constructor does, and what MethodB does, these two operations are otherwise the same.
First, your code is incorrect. There is no "ClassA" class. The class name is A, so the return type should be A not ClassA.
Second, the standard Java coding standards say to start methods and variables with lower case letters. So, your example should have been:
Class A
{
A anA;
B aB;
public int methodA()
{
//some operation
}
}
Class B
{
SomeType x, y;
public static A methodB()
{
//some operation
return obj;
}
}
David's answer shortly before mine is technically correct on points 1 and 2, although he also uses your mistake of calling the A type ClassA. His code for his answer to point 3, though, is incorrect and misleading. I would change his wording to this:
`3)What would the returned objct look like. I mean if my method returned an
integer, it would return some numerical value say '123' . If a method returns
an object of a class, what would be in the returrned value`.
It would be an instance of class A. Similar to creating an instance here:
A objectA = new A();
This method also creates (or in some way gets) an instance:
A objectA = B.methodB();
Without knowing more about what class A is, what its constructor does, and what methodB does, these two operations are otherwise the same.
Case:1
class A
{
private int i=0;
public void display()
{
this.getValue();
}
private int getValue()
{
return i+2;
}
}
Case:2
class B
{
public void display()
{
int i=0;
this. getValue(i);
}
private int getValue(int i)
{
return i+2;
}
}
Does the declaration of "i" in both cases have any great
difference (other than the global access) whenever I call
display() ?
In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.
Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.
Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.
In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.
But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)
In first case i exists outside of any method
In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.