0

In the code

public class Test {
    public static final int var1;
    public static int var2;

    static {
        Test.var2 = 3;
        Test.var1 = Test.var2;
    }

}

javac says

Test.java:8: error: cannot assign a value to final variable var1

But if I remove "Test." from "Test.var1" in the assignment, it compiles without complaint. Why does javac behave this way?

  • 1
    I don't remember the specific answer but it's along the lines of "Java does what Java do" – Rogue May 02 '16 at 20:58
  • 5
    I believe this has to do with how it accesses the `var1` variable. When qualifying the class for the variable, it notices that the variable is final and is being assigned as though it were outside the class (which would be illegal). Whereas the unqualified reference in the static initialization block is considered a "valid" assignment. – callyalater May 02 '16 at 20:59
  • @callyalater I believe that's it – Rogue May 02 '16 at 20:59
  • +1 to @callyalater. You would have the same problem without var2, if you assigned a constant value to var1. – JB Nizet May 02 '16 at 21:00

0 Answers0