简体   繁体   中英

Initializing final fields - Java

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM