How does it actually seal the object so it can not be changed to reference another object?
Careful -- final
is a modifier for the reference to the object. So final
"seals" the reference, not the object.
There are two ways that this "sealing" is done. One is through a compiler check of all final
variables and fields. From the Java Language Specification:
It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment.
A blank final class variable must be definitely assigned by a static initializer of
the class in which it is declared, or a compile-time error occurs.
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared, or a compile-time error occurs.
The other way is through bytecode verification done by the JVM at class load time. The putfield
and putstatic
bytecode instructions throw IllegalAccessError
s if the field being operated on is final
and the bytecode instruction does not occur in a particular place.
However, you have to be a bit careful here -- the final
keyword only "sticks" to fields. Temporary variables and parameters lose their final
-ness at compilation, so the JVM can only verify final
-ness for fields if you use a non-compliant compiler or use bytecode manipulation.
Is it safe to declare a Connection
object as final?
I'm not entirely sure what you mean by "safe", but if you're saying "Won't cause errors in your program", yes, for the most part (the presence of multithreading and/or compile-time constants may or may not change this answer). If you put final
on a reference and your program compiles, then your program should work exactly as it has been working.