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

前端 未结 6 487
无人及你
无人及你 2020-12-04 11:06

Consider the following Java class declaration:

public class Test {

    private final int defaultValue = 10;
    private int var;

    public Test() {
               


        
6条回答
  •  粉色の甜心
    2020-12-04 11:54

    You are referencing to a variable that doesn't exist yet, if it was static it would exist even before the constructor itself.

    But you will face another problem, as defaultValue became static, so all other instances may share the same value which you may don't like it to be:

    public class Test {
    
        private final int defaultValue = 10; //this will exist only after calling the constructor
        private final static int value2= 10; //this exists before the constructor has been called
        private int var;
    
        public Test() {
           // this(defaultValue);    // this method will not work as defaultValue doesn't exist yet
        this(value2); //will work
        //this(10); will work
        }
    
        public Test(int i) {
            var = i;
        }
    }
    

提交回复
热议问题