Java static keyword explanation

introduction

There is a passage in Java programming thought: static method is a method without this. Non static methods cannot be called inside static methods, and vice versa. Moreover, you can call static methods only through the class itself without creating any objects. This is actually the main purpose of the static method.

Although this paragraph only explains the particularity of static method, we can see the basic function of static keyword. In short, it is described in one sentence: it is convenient to call (method / variable) without creating an object.

Static can be used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance.

Usage

1. Static member variable

Static variables belong to classes. There is only one copy in memory. As long as the class where the static variable is located is loaded, the static variable will be allocated space.

2. Static member method

Static methods can be called directly through the class name, and any instance can also be called. Therefore, this and super keywords cannot be used in static methods. You cannot directly access the instance variables and instance methods of the class (that is, member variables and member methods without static). You can only access the static member variables and member methods of the class.

3. Static code block

Static code blocks are independent of member variables and member functions in a class. Note: these static code blocks are executed only once.

4. Static class

Generally, a normal class is not allowed to be declared static, and only an inner class is allowed. At this time, the internal class declared as static can be used directly as a common class without instantiating an external class.

Implementation of singleton mode

The more common way is double detection

public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

There are many other ways to implement the singleton mode. Here we focus on one, which is implemented by using the static internal class. Because the internal static class will only be loaded once, this implementation method is thread safe.

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

    private Singleton() {
    }

    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>