简体   繁体   English

在 Java 中使用 final 变量及其对方法的影响

[英]Using a final variable in java and its implications on methods

Im modifying a large class file.我正在修改一个大类文件。 The easiest way to achieve what I want is to change the class' global variables to 'final' and set the value.实现我想要的最简单的方法是将类的全局变量更改为 'final' 并设置值。 But I havent used finals much.但是我并没有经常使用finals。 Will this cause a problem with the setter methods throughout the file?这会导致整个文件中的 setter 方法出现问题吗? ie what happens when a setter cannot set the variable as the variable is final?即当 setter 无法设置变量时会发生什么,因为变量是最终的? An error?一个错误? Or just ignored?还是只是无视? Thanks.谢谢。

If your fields are final , they must be set either on declaration or in the constructor.如果您的字段是final ,则必须在声明或构造函数中设置它们。 Once set, the compiler will throw an error when set again, because final variables are not allowed to be re-assigned.一旦设置,再次设置编译器会报错,因为final变量不允许重新赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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