Is it okay to make an object of type File, which I later would like to write into, have a final declaration? I'd like to pass it to a Runnable
inner class.

- 85,076
- 16
- 154
- 332

- 1,503
- 3
- 22
- 40
4 Answers
final
declaration allows you to write/read into, but not change the reference of the object.
final File fileRef = new File("/path/to/my/file.txt");
fileRef = new File("/new/path/to/file"); // illegal

- 25,375
- 5
- 50
- 78
There is no problem, final
doesn't mean that the object itself can't alter its state. It just means that the variable can't be reassigned. So it applies to a different thing.
In addition to this, a File
is just an abstract representation of a file system file or folder. You don't write through a File
object, you use it to open a stream (eg. FileWriter
).

- 131,802
- 30
- 241
- 343
Yes. Making a variable final
means you can't change it to point to a different object. You can totally do whatever you want with the object it does point to, though.
final File file = new File("foo");
Runnable r = new Runnable() {
public void run() {
file.renameTo("bar"); // Cool.
file.delete(); // Cool.
file = new File("bar"); // Whoa. Not cool.
}
};

- 349,597
- 67
- 533
- 578
An object from File
class is an abstract representation of a file or directory from the real hard drive. It is not the physical file or folder.
If you mark the variable as final
then it cannot be re assigned. That's all. Marking the variable as final
won't make the physical file immutable. If the Runnable
is created as an anonymous class and the File
variable is local to the method (parameter or local variable), then yes. Otherwise, no.

- 85,076
- 16
- 154
- 332