View RSS Feed

Hibernate

Legal forward reference assignment weirdness on declarations

Rate this Entry
by , 08-11-2011 at 11:38 PM (1415 Views)
Observer the glorious code by your's truly Hibernate:

Java Code:
public class YetAnotherClass
{
    //public static final int YET_ANOTHER_CONSTANT = YET_ANOTHER_CONSTANT; //Compile-time error: illegal forward reference
    public static final int ANOTHER_CONSTANT = YetAnotherClass.ANOTHER_CONSTANT; //OK!

    //public int yetAnotherVariable = yetAnotherVariable; //Compile-time error: illegal forward reference
    public int anotherVariable = this.anotherVariable + 1; //OK!


    public static void main(final String... args)
    {
        System.out.println(ANOTHER_CONSTANT);
        System.out.println(new YetAnotherClass().anotherVariable);
    }
}
Obviously you can not assign a variable to the value of it self before it is declared, hence you
can not write the two commented lines. But if you refer to them in a fully qualified manner, you can!

It is not a bug, it goes hand in hand with the Java specifications.

If you run this code, it prints:
0
1

When value of it the referred to variable is 0, false or null (the default value), if it has not yet been declared.

Submit "Legal forward reference assignment weirdness on declarations" to Facebook Submit "Legal forward reference assignment weirdness on declarations" to Digg Submit "Legal forward reference assignment weirdness on declarations" to del.icio.us Submit "Legal forward reference assignment weirdness on declarations" to StumbleUpon Submit "Legal forward reference assignment weirdness on declarations" to Google

Updated 08-12-2011 at 05:46 AM by Hibernate

Tags: None Add / Edit Tags
Categories
Java's syntax

Comments