Class scope variable vs method scope variable
- by Masud
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?