最近,我发现在一些项目中,他们非常喜欢在方法参数中添加 final 关键字,例如:
public static String getSuffix(final String fileName) {
if (fileName.indexOf('.') >= 0) {
return fileName.substring(fileName.lastIndexOf('.'));
}
return EMTPY_STRING;
}
public HttpResult(final int statusCode) {
this.statusCode = statusCode;
}
最佳答案
它可以帮助您捕获错误。
例如,如果你写:
public HttpResult(final int statusCode) {
statusCode = statusCode;
}
你会得到一个编译错误,因为你正在为你的本地最终变量赋值,而如果你写
public HttpResult(int statusCode) {
statusCode = statusCode;
}
您不会遇到编译错误,但不会分配 statusCode
成员。
关于java - 为什么有些程序员喜欢在方法参数中加上final关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303310/