• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on scope

 
Richard Huang
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one tell me why I can get these output in the cases listed below? thanks!
Case 1

Output:

x in the initializer: 5
x in the instance: 10

Case 2

Output:

x in the initializer: 5
x in the instance: 5

Case 3

Output:

x in the initializer: 5
x in the instance: 100

[This message has been edited by Richard Huang (edited October 03, 2000).]
[This message has been edited by Richard Huang (edited October 03, 2000).]
 
Harry Singh
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Richard,
No matter what you do
"x in the initializer: 5" ---
will always be printed. This is because x is defined as a variable local to that block. It shodows any instance variables that have been defined for the class.
For the first case where you have
x in the instance: 10
Here the 'x' refereed to is the instance variable which you have initialized to 10. When this println is executed there is no other x existing in the class.
For the second case
There is no difference in the code between this case and the first.
For the third case...
Have a look at the code below. Run it and see the o/p. It will clear a lot of things for you...
class TestScope {
int x = 10;// First I do this
// Third I do this
TestScope()
{
System.out.println("x in the constructor before assignment: " + x);
x = 100;
System.out.println("x in the constructor after assignment: " + x);
}

// Second I do this
{
System.out.println("x in the initializer before assignment: " + x);
x = 5;
System.out.println("x in the initializer after assignment: " + x);
}
public static void main(String[] args) {
TestScope t = new TestScope();
System.out.println("x in the instance: " + t.x );
}
}

I have put comments to indicate the order of execution. Hope it helps.
Thanks,
Harry
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic