不能引用“X"在调用超类型构造函数之前,其中 x 是最终变量 [英] Cannot reference "X" before supertype constructor has been called, where x is a final variable

查看:28
本文介绍了不能引用“X"在调用超类型构造函数之前,其中 x 是最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Java 类声明:

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?

推荐答案

代码最初无法编译的原因是因为defaultValue 是类的实例变量Test,意味着当一个 Test 类型的对象被创建时,defaultValue 的唯一实例也被创建并附加到该特定对象.因此,不可能在构造函数中引用 defaultValue,因为它和对象都还没有被创建.

The reason why the code would not initially compile is because defaultValue is an instance variable of the class Test, meaning that when an object of type Test is created, a unique instance of defaultValue is also created and attached to that particular object. Because of this, it is not possible to reference defaultValue in the constructor, as neither it, nor the object have been created yet.

解决办法是让final变量static:

The solution is to make the final variable static:

public class Test {

    private static final int defaultValue = 10;
    private int var;

    public Test() {
        this(defaultValue);
    }

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

通过使变量static,它与类本身相关联,而不是与该类的实例相关联,并在Test 的所有实例之间共享.静态变量是在 JVM 首次加载类时创建的.由于该类在您使用它创建实例时已经加载,因此静态变量已准备好使用,因此可以在类中使用,包括构造函数.

By making the variable static, it becomes associated with the class itself, rather than instances of that class and is shared amongst all instances of Test. Static variables are created when the JVM first loads the class. Since the class is already loaded when you use it to create an instance, the static variable is ready to use and so can be used in the class, including the constructor.

参考文献:

这篇关于不能引用“X"在调用超类型构造函数之前,其中 x 是最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆