• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why it gives ERROR without 'this'

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, can anybody explain me the reason ,Why is to so with(this.i) it does not gives compile time error.

public class Sequence
{
public Sequence() {
System.out.println(" constructor initializer : "+ i );
}

{// line x
System.out.println(" instance initializer :"+this.i);
}

static
{
System.out.println("static initializer");
}

public static void main(String args[])
{
Sequence sq = new Sequence();
}
int i = 20;
}
output is :
static initializer
instance initializer :0
constructor initializer : 20

If at // line x i edit it like this
System.out.println("instance initializer :"+ i );
it gives compile time exception :
illegal forward reference
System.out.println("instance initializer :"+ i );
^
 
Rodrigo Alvarez
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This compiles and run :



But the output is now:

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are using java 1.5 , actually on my comipiler it is showing me a compiler error .

illegal forward reference
System.out.println("instance initializer :"+ i );
^

Hope any body else throw some light on this too.
[ April 15, 2006: Message edited by: faisal usmani ]
 
Henry Wong
author
Marshal
Pie
Posts: 21003
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initialization of instance variables, and executions of instance initializers, are done in order. In this case, it matters on how you typed it in -- think of it as running linearly from top to bottom.

This means that you should not be using forward references -- as variables later in the class are not initialized during initialization of eariler variables (or instance initializers). Actually, they are initialized (as you have seen), but with temporary default values -- like 0, 0.0, or null.

The compiler will do some checking to make sure that these forward references does not exist... but it does a poor job. One way to "trick" it is to reference it, by dereferencing an object -- as you have done by using the this variable. Another way is to call a method which uses it.

Henry
 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry

You made it all clear

--There is no duty more obligatory than the repayment of kindness.
[ April 15, 2006: Message edited by: faisal usmani ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic