Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Prefrence to local ?

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class Shadow
{
int x=10;
void show()
{
int x=1; //Line 100
System.out.println(x);
}
public static void main(String args[])
{new Shadow().show();}
}

why it does not give compile time error at line 100 , as two variables with name x are in scope.
Now how does compiler will decide a reference to x refer to which definition ?
 
Saif Asif
Ranch Hand
Posts: 440
Eclipse IDE Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ,

Well why would the compiler complain at all ? A member variable of the class and a local variable of the method are entirely different in all aspects . I dont think its a matter of preference , but the method show() can not see the variable 'x' directly like this. Non static Member variables have to be accessed via this.x .
 
Zhenyi Luo
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahtab Alam wrote:
class Shadow
{
int x=10;
void show()
{
int x=1; //Line 100
System.out.println(x);
}
public static void main(String args[])
{new Shadow().show();}
}

why it does not give compile time error at line 100 , as two variables with name x are in scope.
Now how does compiler will decide a reference to x refer to which definition ?


Because you are shadowing variable in Java
 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now compiler complaint a Local variable x and a block variable x


class R
{
public static void main(String args[])
{
show(10);
}
static void show(int x)
{
for(int x=1;x<2;x++)
System.out.println(x);
}
}


compiler say x is already defined in show(int)

When scope conflict occurs then there is problem.
So why there is no scope conflict in the first code
 
Zhenyi Luo
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahtab Alam wrote:Now compiler complaint a Local variable x and a block variable x


class R
{
public static void main(String args[])
{
show(10);
}
static void show(int x)
{
for(int x=1;x<2;x++)
System.out.println(x);
}
}


compiler say x is already defined in show(int)

When scope conflict occurs then there is problem.
So why there is no scope conflict in the first code

Shadowing happens when local variable "shadow" the instance variable temporarily using the same name, but local variable could not "shadow" another local variable. Refer to this discussion: http://stackoverflow.com/questions/4623334/question-about-variable-scope-and-shadowing-in-java
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic