Class scope variable vs method scope variable
Posted
by
Masud
on Stack Overflow
See other posts from Stack Overflow
or by Masud
Published on 2013-10-20T02:33:45Z
Indexed on
2013/10/20
3:54 UTC
Read the original article
Hit count: 581
I know that variable scope is enclosed by a start of block {
and an end of block }
. If the same variable is declared within the block, then the compile error Variable already defined
occurs. But take a look at following example.
public class Test{
int x=0;// Class scope variable
public void m(){
int x=9; //redeclaration of x is valid within the scope of same x.
if(true){
int x=7; // but this redeclaration generates a compile time error.
}
}
Here, x
can be redeclared in a method, although it's already declared in the class. But in the if
block, x
can't be redeclared.
Why is it that redeclaration of a class scope variable doesn't generate an error, but a method scope variable redeclaration generates an error?
© Stack Overflow or respective owner