在构造器中调用this(s)或super(s)

问题描述见stackoverflow:
stackoverflow:Cannot reference “X” before supertype constructor has been called, where x is a final variable
看完stackoverflow上的解答后我反而更迷惑了(也有可能有是英语不过关的原因。。。)。因为我知道对象字段加载先于构造器,构造器创建时字段已经存在,那为什么会出现调用错误呢?
链接中得票最高的解答有这么一句:

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 ....

这段话意思是说当对象加载时,字段实例也被加载,就因为这个原因,所以错误。????这话说的好迷,就算这个非常'unique'的字段被加载进了非常'particular'的对象中,那构造器也是后一步才加载的事啊,怎么就能得出错误原因了呢?

holdtom
浏览 715回答 1
1回答

红颜莎娜

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; } } 这里 defaultValue 是类的实例 变量,在类实例创建后才会被创建,而类的创建是通过构造函数创建的,当一个构造函数 A 调用另一个构造函数 B 的时候(A、B参数不同),B 必须在 A 的第一行说明它会替代 A 的功能,所以 B 没执行的时候 其实 实例 还没有初始化,类实例还没创建,当然不能使用实例变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java