Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should initialized final fields that are immutable always be made static?

Tags:

java

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";
}
like image 454
user1027169 Avatar asked Jan 28 '23 13:01

user1027169


1 Answers

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).

like image 147
Pshemo Avatar answered Jan 31 '23 03:01

Pshemo