A quick explanation of the five types of static in Java

Overview

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.

1. static method

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

2. static field

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.

3. [For intermediate users] static import

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.

4. [For intermediate users] static inner class

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

5. [For intermediate users] static initializer

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);
}

Reference material

-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

A quick explanation of the five types of static in Java
Measure the size of a folder in Java
A quick review of Java learned in class
A quick review of Java learned in class part4
A quick review of Java learned in class part3
A quick review of Java learned in class part2
List of types added in Java 9
Get the public URL of a private Flickr file in Java
Let's create a TODO application in Java 1 Brief explanation of MVC
Let's create a TODO application in Java 5 Switch the display of TODO
A quick look back at Java over the last five years
Get the result of POST in Java
The story of writing Java in Emacs
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
The story of forgetting to close a file in Java and failing
Sample program that returns the hash value of a file in Java
How to get the absolute path of a directory running in Java
Find the maximum and minimum of the five numbers you entered in Java
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
The story of learning Java in the first programming
Feel the passage of time even in Java
Import files of the same hierarchy in Java
Validate the identity token of a user authenticated with AWS Cognito in Java
Sample code to get the values of major SQL types in Java + MySQL 8.0
Get the URL of the HTTP redirect destination in Java
Specify the encoding of static resources in Spring Boot
Count the number of occurrences of a string in Ruby
A note for Initializing Fields in the Java tutorial
[Java] Get the file in the jar regardless of the environment
[Java] When writing the source ... A memorandum of understanding ①
I summarized the types and basics of Java exceptions
Change the storage quality of JPEG images in Java
A survey of the Kubernetes native Java framework Quarkus
Summarize the additional elements of the Optional class in Java 9
[Java] Integer information of characters in a text file acquired by the read () method
A memo about the types of Java O/R mappers and how to select them
Understand in 3 minutes! A very rough explanation of the difference between session and cookie
Was done in the base year of the Java calendar week
A brief explanation of a maze game made in Java for a cousin of an elementary school student
A quick explanation of each item in new_framework_defaults_6_1.rb, which is a new application setting added in rails 6.1.
Let's make a calculator application in Java ~ Display the application window
Check the dependency of a specific maven artifact in Coursier
A program (Java) that outputs the sum of odd and even numbers in an array
Determine that the value is a multiple of 〇 in Ruby
Considering the adoption of Java language in the Reiwa era ~ How to choose a safe SDK
Activate Excel file A1 cell of each sheet in Java
Sample code to get the values of major SQL types in Java + Oracle Database 12c
Find a subset in Java
Explanation of the FizzBuzz problem
Create a method to return the tax rate in Java
Count the number of digits after the decimal point in Java
A program that counts the number of words in a List
Implementation of gzip in java
How to derive the last day of the month in Java
I tried to make a client of RESAS-API in Java
Benefits of Java static method
Implementation of tri-tree in Java