The role of the static keyword in java, the javastatic keyword
The static keyword in java has two main functions:
1. Allocate a single bucket to a specific data type or object, regardless of the number of created objects.
Second, associate a method or attribute with a class rather than an object.
In Java, static is mainly used in five scenarios: member variables, member methods, code blocks, internal classes, and static guide packages.
Basic usage:
The following are examples of various static usage
Static modifier member variables and member Methods
Several conclusions:
/** * * Created by ascend on 2017/6/9 13:51. */public class Test { public static void main(String[] args) throws ClassNotFoundException { Class.forName("net.liebao.test.A"); }}class A { static { System.out.println("A.static initializer"); } public A() { System.out.println("A.A"); }}
Output:
A.static initializer
Conclusion 1: static resources belong to the Class but are independent from the Class. Static resources are loaded at Class initialization (earlier than new), such as Class. forName ("xxx") can load static resources of a class, but there is no new.
Conclusion 2: static resources (static member variables, static member methods, the same below) cannot access non-static resources. Non-static resources are generated only when they are new, so they cannot be accessed. Otherwise, non-static resources can access static resources.
Conclusion 3: static resources can access static resources, but it should be noted that static resources can be assigned values for static resources defined after it, but cannot access static resources defined after it
Another common purpose is static Singleton mode.
We all know that the singleton mode is characterized by that the class can only have one instance. To implement this function, you must hide the class constructor, that is, declare the constructor as private, and provides a method to create an object. Because the constructor object is declared as private, you cannot directly create this type of object. You can only obtain the class object through the methods provided by this class, to achieve this purpose, you can only declare the method for creating an object as static. The program instance is as follows:
Class Singleton {private static Singleton instance = new Singleton (); // private constructor private Singleton () {} public static Singleton getInstance () {return instance ;}}
The preceding Singleton mode is the hunger mode;
Codeword is not easy, Respect Original, reprint Please note: http://www.cnblogs.com/adeng/p/6971366.html