I have difficulties in naming the two kinds of scopes that I see in Java:
class Fun {
int f = 1;
void fun() {
int f = 2;
while(true){
int f = 3;
int g = 1;
}
int g = 2;
}
}
The case is mostly with f = 3
and g = 2
;
A while
statement doesn't introduce a new scope, so I can't create a while-local variable named f
. But if I create a local variable named g
then I can "re-create" it after the loop. Why? I know it's no longer accessible, but if the compiler checks accessibility then it almost checks scopes..
So I was wondering what is the deal here, what are these concepts called? Is it the same as in C++?
I just managed to install g++ and tried it out myself:
#include <iostream>
using namespace std;
int main(){
int f = 0;
for(int i=0; i<1; i++){
int f = 1;
cout << f << endl;
{
int f = 2;
cout << f << endl;
}
}
cout << f << endl;
}
So apparently C++ treats all scopes equally!
The term "instance variable" is another name for non-static field. The term "class variable" is another name for static field. A local variable stores temporary state; it is declared inside a method.
Global variables are declared outside all the function blocks. Local Variables are declared within a function block. The scope remains throughout the program. The scope is limited and remains within the function only in which they are declared.
Once you left the while{} loop g went out of scope as soon as you left it. It was then valid to declare g again.
Local variables are only in scope for the duration of the block in which they are declared.
To go into more detail:
f
is object scope. Its accessible from the object at all
times. f
is local scope. You access it using f
, you
can still access the object scope f
using this.f
. The third f
is trying to create a second local scope f
. That is invalid.
The first g
is creating a local scope g
.
g
is creating a second local scope g
but the first one has already gone out of scope and disappeared.So the only invalid declaration is the third f.
There is a third type of scope which is where static variables are declared - these are variables that are shared between every instance of a class.
There are a number of names for the types, some of the most common are Local Variables, Instance Variables (also known as Fields) and Class Variables (also known as Static Fields). You also have method parameters but that's just a different way of getting a Local Variable.
For further reading:
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