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

前端 未结 6 498
无人及你
无人及你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 11:50

    Rule : Every constructor must execute super class's constructor before executing itself.

    So the first line of every constructor is super() or may be this() and you are send the defaultValue to the this class constructor which(defaultValue) is not existed yet hence there is compile time error.

    You can made defaultValue as static and since static variable is created as class is loaded to memory so defaultValue is available at the line this(defaultValue).

提交回复
热议问题