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";
}
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 haveand each instance is supposed to use its own
lock
object for synchronization (likesynchronize(lock){...}
). Despite the fact thatObject
is immutable, makinglock
static is not what we want (value oflock
should not be shared, but separate for each instance).