且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我为什么要使用关键字“final”?在Java中的方法参数?

更新时间:2022-11-23 09:53:55

有时很高兴能够明确(为了便于阅读)变量不会改变。这是一个简单的例子,使用final可以节省一些可能的麻烦

Sometimes its nice to be explicit(for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches

public void setTest(String test) {
    test = test;
}

如果您在设置器上忘记了'this'关键字您想要的变量设置没有设置。但是,如果您在参数上使用了final关键字,则会在编译时捕获该错误。

if you forget the 'this' keyword on a setter the variable you want to set doesn't get set. However if you used the final keyword on the parameter then the bug would be caught at compile time.