Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance variable definitions and instance blocks

Tags:

java

I have the following piece of code-

{s = "Hello";}
String s;

This compiles fine, implying that the variable definitions are executed before the instance blocks. However, if I use the following code instead, it does not compile ("error: illegal forward reference").

{s = "Hello"; String ss = s;}
String s;

So it is not possible to use the value of 's' on the right-hand side of a statement in an instance block that comes BEFORE the variable definition. Is there a sane explanation of what is happening behind the scenes, or is this simply an idiosyncratic feature of Java?

P.S. I have seen a similar question asked before, the only explanation given there is that it is a feature of Java. I am writing this to ask the community if that is indeed the final word on this question.

like image 638
user3516726 Avatar asked Sep 17 '14 16:09

user3516726


1 Answers

JLS §8.3.3 ("Forward References During Field Initialization") sheds some light here:

Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. Specifically, it is a compile-time error if all of the following are true:

  • The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;

  • The use is a simple name in either an instance variable initializer of C or an instance initializer of C;

  • The use is not on the left hand side of an assignment;

  • C is the innermost class or interface enclosing the use.

The first bullet would apply to your example.

As for the "why" part, "why" is usually a tricky question with language design, but in this case they helpfully added this note further down:

The restrictions above are designed to catch, at compile time, circular or otherwise malformed initializations.

like image 115
T.J. Crowder Avatar answered Oct 04 '22 02:10

T.J. Crowder