Should initialized end fields always be static unchanged?

I was wondering if there would ever be a legal use case for non-empty / initialized immutable leaf fields.

In other words:

class Foo {
  private final String bar = "bar";
}

Against

class Foo {
  private static final String BAR = "bar";
}
+4
source share
1 answer

The answer, as in most cases: depends on .

What does it mean to do it static? Effectively this means that all instances use the same value for this field.

In most cases, an immutable object can be accessed by all instances without problems. As in this case, it makes sense to make it static, since you want all instances of your class to use the same value for this field.

, , mutable, monitor, . ,

private final Object lock = new Object(); 

lock (, synchronize(lock){...}). , Object , lock static , ( lock , ).

+8

Source: https://habr.com/ru/post/1694391/


All Articles