The role and usage of the Java keyword static

The previous article reviewed the execution order ( jump ) of static code blocks, construction code blocks, and construction methods . This article mainly reviews the function and usage of the keyword static.

Knowledge point review:
If accessing variables or methods is generally to create objects of this type and call them (of course, reflection is also a case, not discussed here). Therefore, in order to facilitate calling variables or methods without creating an object, the static keyword was born at this time.

Static syntax:
through class name, static variable or class name. static method

Like the following:

public class StaticTest {
    
    
	//定义静态变量
    static String name;
    //定义静态方法
    public static void fly(){
    
    
        System.out.println(name+"翩翩起舞");
    }
    public static void main(String[] args) {
    
    
        StaticTest.name = "蒲公英";
        StaticTest.fly();
    }
}

In addition to these, the static keyword has those unique features. Let us continue to look down.

1. The variable or method modified by static is independent of any object of the class. In other words, variables and methods do not belong to any instance object, but are shared by instance objects of the class. How to understand being shared by instance objects of this class? Simply put, every object created can call static variables and static methods (but it is not recommended to access through object references).

Modify the above code:

public class StaticTest {
    
    
    static String name;
    public static void fly(){
    
    
        System.out.println(name+"翩翩起舞");
    }
    public static void main(String[] args) {
    
    
        StaticTest.name = "蒲公英";
        StaticTest s1 = new StaticTest();
        StaticTest s2 = new StaticTest();
        System.out.println(s1.name);
        s2.fly();
    }
}

Analysis:
Compare the above code. This time I created two objects, s1 and s2, to call variables and methods.
Obviously the code does not look concise.

For member variables, it simplifies the way to initialize variables through parameterized construction and setters. For methods, they can be called without creating an object (which means that variables and methods modified by static have priority over the existence of objects).

So what are the benefits?

2. The static variable value allocates space when the class is loaded, and will not be re-allocated when the class object is created later.

Look at an example:

public class Counter {
    
    
    static int count;
    public Counter() {
    
    
        count++;
        System.out.println(count);
    }
    public static void main(String[] args) {
    
    
        Counter counter = new Counter();
        Counter counter2 = new Counter();
        Counter counter3 = new Counter();
    }
}

operation result:

1
2
3

Analysis: In simple terms, static variables will only get the memory space once, and any object modification to him will be retained. Therefore, count is incremented by 1 every time an object is created, and the final result is 3.

Counter-example verification:

public class Counter {
    
    
    int count;
    public Counter() {
    
    
        count++;
        System.out.println(count);
    }
    public static void main(String[] args) {
    
    
        Counter counter = new Counter();
        Counter counter2 = new Counter();
        Counter counter3 = new Counter();
    }
}

operation result:

1
1
1

Analysis: Create the member variable count and increment it in the construction method. The member variable count will get memory when the object is created, and each object will have a copy of count, so the count will not increase as the number of objects increases.

3. The static code block is executed when the JVM loads the class, and executed once.
public class PropertiesTest {
    
    
    public static List<String> list = new ArrayList<String>();

    static {
    
    
        list.add("奋斗志向从处何来?");
        list.add("从读书学习中来,从勤奋中来,");
    }

    static {
    
    
        list.add("从思考中来,从实践中而来。");
    }

    public static void print() {
    
    
        if (list.size() == 0) {
    
    
            throw new RuntimeException("集合为空");
        }

        for (String ele : list) {
    
    
            System.out.print(ele);
        }
    }

    public static void main(String[] args) {
    
    
        print();
    }
}

Output positive energy:
where does the aspiration for struggle come from? Come from studying, come from diligence, come from thinking, come from practice.

(Quotations from Struggle )

When to use static code blocks?
Generally during initialization operations, such as reading configuration file information.

Supplement: The static code block is executed before the main method.
The verification is as follows:

public class MainTest {
    
    
    static {
    
    
        System.out.println("静态代码块");
    }

    public static void main(String[] args) {
    
    
        System.out.println("main方法");
    }
}

operation result:

Static code block
main method

4. Static inner class
Define an inner class plus static, it becomes a static inner class. There is a piece of code in the wrapper class Integer that looks like this.

 private static class IntegerCache {
    
    
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
    
    
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
    
    
                try {
    
    
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
    
    
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
        private IntegerCache() {
    
    }
    }

The cleverness of this design is that the code block in the Integer static inner class is instantiated in advance with the value of the range [-128~127] and stored in the cache array.

The singleton pattern we are familiar with

public class Singleton {
    
    
    //私有构造方法
    private Singleton() {
    
    }
    //静态内部类
    private static class SingletonHolder{
    
    
       public static final Singleton instance = new Singleton();
    }
    //公共的静态方法
    public static Singleton getInstance() {
    
    
        return SingletonHolder.instance;
    }
    public static void main(String[] args) {
    
    
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance);
        System.out.println(instance1);
    }
}

Analysis: When
the Singleton class is loaded for the first time, the instance is not initialized. Only when the getInstance() method is called for the first time, the Java virtual machine starts to load the SingletonHolder and initialize the instance. This not only ensures thread safety, but also ensures the uniqueness of the Singleton class. Sex.

Note:

1. Static can only access static
2. Non-static can access both static and non-static. (Because variables and methods modified by static have priority over objects)

The above is the learning of the keyword static. If it's useful to you, remember to Sanlian.

Guess you like

Origin blog.csdn.net/lirui1212/article/details/115254985