Class member, Class
5.3
5.3.1. Understanding class objects
Package code; public class NullAccessStatic {private static void test () {System. out. println ("static modified class method");} public static void main (String [] args) {NullAccessStatic nas = null; // use a null object to call the static method nas of the class. test ();}}
Static modification class Method
Indicates that the null object can access the class members of the class,
When a null object accesses an instance Member, The NullPointerException is thrown,
The static initialization block is used to perform class initialization. During the class initialization phase, the system calls the static initialization block of the class to initialize the class. Once the class initialization is complete, static initialization blocks will never get execution opportunities
For the static keyword, there is a very important rule that class members cannot access instance members. Because the class members belong to the class, the scope of the class members is greater than that of the instance members. It is entirely possible that the class members have been initialized and the instance members have not yet initialized, so they cannot be accessed.
5.3.2 Singleton class
If a class can only create one instance, this class is called a singleton class.
To prevent other classes from creating instances of this classThe constructor of this class uses private ModifierTo hide all constructors of the class.
According to the good encapsulation principle, once the constructor of this class is hiddenProvides a public method as the access point of this class, used to create the object of this class, and this method must be modified using static(Because no object exists before calling this method, it is impossible to call this method as an object and only a class)
In addition, this class must cache created objects. Otherwise, this class cannot know whether an object has been created, so it cannot guarantee that only one object is created,
Package code; class Singleton {public static Singleton instance; private Singleton () {} public static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}} public class SingletonTest {public static void main (String [] args) {Singleton s1 = Singleton. getInstance (); Singleton s2 = Singleton. getInstance (); System. out. println ("s1 and s2 are equal" + (s1 = s2 ));}}
Is s1 and s2 equal to true?