开发者

Initializing final fields - Java

开发者 https://www.devze.com 2023-01-10 08:32 出处:网络
I would like to know if there\'s a compiler option that could allow me to remove/cure the error that comes up (\"variable X migh开发者_StackOverflow中文版t not have been initialized\") when I compile

I would like to know if there's a compiler option that could allow me to remove/cure the error that comes up ("variable X migh开发者_StackOverflow中文版t not have been initialized") when I compile a class who has a final field in it. Or even better would be to have the final fields initialized to the default java value.

Thanks,

ExtremeCoder


The way to cure the error is fix the code: make sure you initialize the value explicitly. I don't believe there's any option to just ignore the error.

One way of mimicking this is to give the constructor local variables set to the Java default values, then replace them during the course of the constructor. At the end of the constructor, set the field values to those of the local variables.

Mind you, if you've got a lot of code in your constructor you might want to consider refactoring anyway...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号