• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static block

 
krussi rong
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
here is the question:
public class Q8
{
int i=20;
static
{
int i=10;
}
public static void main(String[] args)
{
Q8 a = new Q8();
System.out.println(a.i);
}
}
So why can delare the same variable in the
static block with the instance variable?
Does the static block's variable 's scope
only in the static block? if not how can access
the static block variable in the main method?
thanks
Krussi
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by krussi rong:
Hi,
here is the question:

So why can delare the same variable in the
static block with the instance variable?
Does the static block's variable 's scope
only in the static block? if not how can access
the static block variable in the main method?

The variable i, within the static block, has scope only within that block. In fact, you're hiding the instance member i with that local variable. There is no way to access that variable once you've reached main because, by that point, the variable has gone out of scope.
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic