Reader B commented on the last post in the series, “I’m guessing the next post is titled, ‘Holy crap, you don’t know the static keyword.'” I can only say that b was half right. How could a blogger as talented as me be correctly guessed by readers? It had to be something different, so you saw the title of this article.

Seven years ago, I returned from Suzhou, a city with many beautiful women, to Luoyang, a city with many beautiful women. With the mentality of “moving from a second-tier city to a third-tier city”, I sent many resumes and interviewed many interviewers, but only two or three of them satisfied me. One of them, Lao Ma, is still alive in my wechat address book. He threw an interview question at me: “Dude, say Java static.”

At that time, I was 23 years old and in the prime of life. I thought I could answer all the interview questions fluently, but unexpectedly, I was “baffled” — Luoyang, the desert of the Internet, also had technical experts. When I recall it now, I blush with shame on my face: it’s mainly because I was too good at that time.

Anyway, after years of hard work, I now have a solid technical foundation and am able to write an article on the Java static keyword – as long as I can give some reference to beginners, I feel very satisfied.

Let me start by outlining:

The static keyword can be used for variables, methods, code blocks, and inner classes to indicate that a particular member belongs only to the class itself, and not to an object of that class.

01. Static variables

A static variable is also called a class variable. It belongs to a class, not an object of that class.

public class Writer {
    private String name;
    private int age;
    public static int countOfWriters;

    public Writer(String name, int age) {
        this.name = name;
        this.age = age;
        countOfWriters++;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code

CountOfWriters is called a static variable, which is distinct from the name and age member variables because it is preceded by the modifier static.

This means that no matter how many times the class is initialized, the value of the static variable is shared among objects of all classes.

Writer w1 = new Writer("Silent King II.".18);
Writer w2 = new Writer("Silent King three.".16);

System.out.println(Writer.countOfWriters);
Copy the code

By that logic, you should be able to deduce that countOfWriters should be written with a 2 instead of a 1. From a memory perspective, static variables will be stored in a specific pool in the Java virtual machine called “Metaspace” (meta-space, after Java 8).

Static variables are very different from member variables. The value of a member variable belongs to an object and is not shared between different objects. A static variable is not. It can be used to count the number of objects because it is shared. Like countOfWriters in the example above, it has a value of 1 when one object is created and 2 when two objects are created.

A quick summary:

1) Since static variables belong to a class, they should be accessed directly by the class name rather than by an object reference;

2) Access static variables without initializing the class.

public class WriterDemo {
    public static void main(String[] args) {
        System.out.println(Writer.countOfWriters); / / 0}}Copy the code

02. Static methods

Static methods, also known as class methods, are similar to static variables in that they belong to a class rather than an object of that class.

public static void setCountOfWriters(int countOfWriters) {
    Writer.countOfWriters = countOfWriters;
}
Copy the code

SetCountOfWriters () is a static method decorated with the static keyword.

If you’ve ever worked with the Java.lang. Math class or some of Apache’s utility classes (such as StringUtils), static methods will be familiar.

Almost all of the methods of the Math class are static and can be invoked directly from the class name, without the need to create an object for the class.

A quick summary:

1) Static methods in Java are resolved at compile time because static methods cannot be overridden (method overwriting occurs at run time, for polymorphism).

2) Abstract methods cannot be static.

3) Static methods cannot use this and super keywords.

4) Member methods can directly access other member methods and member variables.

Member methods can also directly method static methods and static variables.

6) Static methods can access all other static methods and static variables.

7) Static methods cannot directly access member methods and variables.

Static code blocks

Static blocks of code can be used to initialize static variables, although static methods can also be initialized directly at declaration time, but sometimes we need more than one line of code to complete the initialization.

public class StaticBlockDemo {
    public static List<String> writes = new ArrayList<>();

    static {
        writes.add("Silent King II.");
        writes.add("Silent King three.");
        writes.add("The Silent King iv.");

        System.out.println("The first piece");
    }

    static {
        writes.add("The Silent Five.");
        writes.add("The Sixth King of Silence.");

        System.out.println("The second piece"); }}Copy the code

Writes is a static ArrayList, so it’s unlikely to be initialized at declaration time, so it needs to be initialized in a static block of code.

A quick summary:

1) A class can have more than one static code block.

2) Static code blocks are parsed and executed in the same order as their position in the class. To verify this, add an empty main method to the StaticBlockDemo class, and the result will look like this:

The first piece, the second pieceCopy the code

Static inner class

Java allows us to declare an inner class within a class, which provides a compelling way to use a few variables in just one place, making code more organized and readable.

There are four common inner classes: member inner class, local inner class, anonymous inner class and static inner class. Due to space reasons, the first three are not covered in this article, but will be discussed in more detail later.

public class Singleton {
    private Singleton(a) {}

    private static class SingletonHolder {
        public static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance(a) {
        returnSingletonHolder.instance; }}Copy the code

This is a way to create a Singleton. Instance is not initialized when the Singleton class is first loaded. The Java virtual machine starts loading the SingletonHolder and initializing instance only when the getInstance() method is called for the first time, ensuring not only thread-safety but also the uniqueness of the Singleton class. However, a more elegant way to create singletons is to use enumerations.

A quick summary:

1) A static inner class cannot access all member variables of the outer class.

2) Static inner classes can access all static variables of external classes, including private static variables.

3) External classes cannot be declared static.

Got it? To learn is to earn.

I am silent King 2, an interesting programmer. If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you.

Interview on GitHub

Original is not easy, do not want a free ticket, please point a praise for this article, it will be the strongest power FOR me to write more high-quality articles.