There are five types of Java "static". However, each is similar and different. In this article, I will explain the points to avoid getting stuck in the pitfalls of each static. If you want to know more details, please refer to the reference materials at the end of the article.
If a method has a static modifier, it becomes a static method.
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
The static method seems convenient at first glance (it looks easy to use) because it can be called without newing the instance. However, [to make unit tests easier to write, it should be used only for "routine processing"](https://qiita.com/flyaway/items/34069ca6ad9ada4c0fef#%E5%95%8F%E9%A1% 8C% E3% 82% 92% E8% A7% A3% E6% B1% BA% E3% 81% 99% E3% 82% 8B% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E5% 8E% 9F% E5% 89% 87% E3% 83% AB% E3% 83% BC% E3% 83% AB).
If a field has a static modifier, it becomes a static field.
public static final double PI = 3.14159265358979323846;
As mentioned above, it can be used as a constant by ** using it together with the final modifier **. By using it together with the final modifier, it is possible to prevent bugs such as the value being rewritten somewhere in the program and an incorrect calculation result being output.
Depending on the system design, it can also be used to hold a cache.
It will be possible to call static fields and static methods of external classes without specifying a class name.
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class SampleTest {
@Test
public void Test() {
assertThat("foo", is("foo"));
}
}
In the above sample, ʻAssert.assertThat and
Matchers.is` can be described by omitting the class name.
If the static modifier is given to the inner class, it becomes a static inner class.
public class Outer {
public static class Inner {
//static inner class
}
}
Non-static inner classes can also access parent class fields and instance methods. Therefore, it holds a reference to the parent class.
However, unnecessary references to the parent class may have an adverse effect on memory and GC [^ 1]. ** If the inner class can be made static, it should be made static ** [^ 2].
The process described in the block below is called when the class is accessed for the first time.
static {
//processing
}
Specifically, it is used for initializing a collection of static fields [^ 3].
public static final List<String> LIST;
static {
List<String> tmp = new ArrayList<>();
tmp.add("foo");
tmp.add("bar");
LIST = Collections.unmodifiableList(tmp);
}
-Carefully explain Java static methods! Let's learn usage examples and ideas together! -How to use and utilize Java static fields! With easy-to-understand explanations! -Static story of Java
Recommended Posts