I was wondering if there would ever be a legitimate use case for non-blank/initialized immutable final fields.
In other words:
class Foo {
private final String bar = "bar";
}
Versus
class Foo {
private static final String BAR = "bar";
}
Answer, as in most cases is: it depends.
What does it mean to make it static
? Effectively it means to let all instances use same value of that field.
Most of the time immutable object could be shared among all instances without problems. Like in this case it makes sense to make it static since you want all instances of your class to use same value of that field.
But lets not forget that even if object is immutable it still has mutable property like monitor
which is used in synchronization mechanisms. Lets say your class have
private final Object lock = new Object();
and each instance is supposed to use its own lock
object for synchronization (like synchronize(lock){...}
). Despite the fact that Object
is immutable, making lock
static is not what we want (value of lock
should not be shared, but separate for each instance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With