为什么必须在构造函数完成之前初始化最终变量? [英] Why must a final variable be initialized before constructor completes?
本文介绍了为什么必须在构造函数完成之前初始化最终变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么必须在构造函数完成之前初始化最终变量?
Why must a final variable be initialized before constructor completes?
public class Ex
{
final int q;
}
编译此代码时出现错误
错误:变量q可能尚未初始化
推荐答案
官方的原因是它由 Java语言规范8.3.1.2 :
最后一个空白必须在声明它的类的每个构造函数的末尾明确赋值实例变量;否则会发生编译时错误。
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
空白的final是一个最终变量,其声明缺少初始值(即你所描述的)。
A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).
这篇关于为什么必须在构造函数完成之前初始化最终变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文