I've just come across some code that's confusing me slightly; there are really 2 variations that I'd like to clarify.
Example 1:
public String getFilepath(){
final File file = new File(this.folder, this.filename);
return file.getAbsolutePath();
}
What would be the purpose of declaring file
"final
"? Since Java primitives are passed by value, and getAbsolutePath()
is just returning a String
, the variable won't be final
on the other side (calling method), will it? And since the file
variable only exists within the scope of these 2 lines, I can't really see any purpose of the final
keyword. Is there something I'm missing? Anyone see a reason to do this?
Example 2:
public String getFilepath(){
final File file = new File(this.folder, this.filename);
return file;
}
Since here the actual object is being returned... Does that mean the file
variable will be constant/final
on the other side...? It doesn't seem to make sense.
In general, it seems to me that you pass a variable, without it's access type. As in, I can have a private
variable in a function with a public
get function that returns it - but the variable that receives it by calling the function has to specify an access modifier. So if it specifies public
, the returned variable will be public
in that scope. If it specifies private
, the returned variable will be private
in that scope. Is there a difference with final
? Is the "constancy" of a variable something that can be passed? This strikes me as rather improbable, considering what I know of Java.
Or am I missing the point entirely and there's some other purpose of the final
keyword in the above code?
Edit:
I checked back with the original developer who wrote the code, and he said he only put the final
keyword in because he had originally thought the method would be a lot longer and wanted to ensure that the file stayed constant throughout. He also said that he generally declares variables that should not be changed as final
, as a rule across the board and sort of on principle - a point that both the answers below mentioned. So it seems I was reading too much into a simple extra keyword included for standards reasons. Thanks everyone!