Alex Rivera | Logout

Cannot reference "X" before supertype constructor has been called, where x is a final variable

Asked 2012-06-09T19:05:16.647
94

Consider the following Java class declaration:

public class Test {

    private final int defaultValue = 10;
    private int var;

    public Test() {
        this(defaultValue);    // <-- Compiler error: cannot reference defaultValue before supertype constructor has been called.
    }

    public Test(int i) {
        var = i;
    }
}

The code will not compile, with the compiler complaining about the line I've highlighted above. Why is this error happening and what's the best workaround?

Edit
Report

1 Answer

9

It is because the defaultValue is an member of Test 's instance which is under construction (not yet created)

If you had it static it were loaded when your class loads by classloaders

answered 2012-06-09T19:08:03.130

Your Answer