• Post Reply Bookmark Topic Watch Topic
  • New Topic

Initializer block problem ....'Illegal forward reference'  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In initializer block ->

{
System.out.println("this.nsf1 : "+this.nsf1);
nsf1=10;
nsf1=sf1;
//////////// int a=2*nsf1;

int b=nsf1=20;

System.out.println("this.nsf1 : "+this.nsf1);
int c=this.nsf1;
}
int nsf1;
static int sf1;

this code works fine. Even though i have declared 'nsf1' later and used it before at 'nsf1=sf1;' & 'this.nsf1' . BUT THE PROBLEM ARISES WHEN I UNCOMMENT THE COMMENTED CODE -'int a=2*nsf1;' , IT GIVES AN COMPILE TIME ERROR 'Illegal forward reference int a=2*nsf1;'

If i'm able to use/access the variable nsf1's value in this block then why does it gives this error of 'Illegal Forward Reference' .

When i'm using it at the left hand, it works fine.

why is it that when i use it at right hand here, it gives this error.... but again when i use it in line - 'int b=nsf1=20;' ... it works fine .. ??
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paragraph 8.3.2.3 of the Java Language Specification explains this:

"The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

* The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C."
* The usage is not on the left hand side of an assignment."



Move the declaration of the member variable nsf1 before the initializer:

[ October 14, 2006: Message edited by: Jesper Young ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!