This is the 11th day of my participation in Gwen Challenge

static:

Among Java keywords, static and final are two that we must master. Different from other keywords, they can be used in a variety of ways, and in a certain environment, can improve the performance of the program, optimize the structure of the program. Let’s look at the use of static.

1. Application:

The static keyword has two uses:

  • First, allocate a single storage space for a particular data type or object regardless of the number of objects created
  • Second, implement a method or property associated with a class rather than an object

Specifically, there are four main uses of static in the Java language: member variables, member methods, code blocks, and static guides

1). Static modify member variable:

Java classes provide two types of variables: static variables that are modified with the static keyword and instance variables that are not modified with the static keyword. A static variable is a class and has only one copy in memory. As soon as the class in which the static variable resides is loaded, the static variable is allocated space and is therefore available. There are two ways to refer to static variables: class. Static variables “and” objects. Static variable “;

// Static variable:
Student.id;                     Static variable; Student is the class and ID is the static attribute
// Static variable:
Student student=new Student;
student.id;                     // object. Static variable; Student is the student object and id is a static attribute
Copy the code

The instance variable belongs to the object, only after the object is created, the instance variable will be allocated memory space, can be used, it exists in the memory of multiple copies, only with “object. Instance variable.

Student student=new Student();
student.id;           Student is the object whose id is a non-static variable
Copy the code

We also use examples to illustrate the use of static modifiers:

public class Person {
    String name;
    int age; 
    public String toString(a) {
        return "Name:" + name + ", Age:" + age;
    }
   
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.name = "zs";
        p1.age = 10;
        Person p2 = new Person();
        p2.name = "ls";
        p2.age = 12; System.out.println(p1); System.out.println(p2); }}Copy the code

The output is as follows:

We are familiar with the above code. Each object constructed according to Person exists independently and has its own independent member variables, which do not affect each other. Their representation in memory is as follows:

As you can see from the figure above, objects referenced by the variables P1 and P2 are stored at different addresses in the heap region of memory, so they do not interfere with each other. But actually, in this, we’ve omitted some important information, and I’m sure you’ll all know that the object’s member properties are all here, and each object is holding their own, so what about their methods? In fact, no matter how many objects a class creates, their methods are the same:

From the figure above, we can see that the methods of both Person objects really just point to the same method definition. This method definition is an immutable region of memory (partitioned by the JVM) that we tentatively call static storage. This store not only holds the method definitions, but actually, in a larger sense, it holds the class definitions, and when we generate objects through New, we create objects based on the class definitions defined here. Multiple objects can only correspond to the same method, there is a reason let us fully convinced, that is the object, no matter how much they approach is always the same, although the final output will be different, but the method is always desired results to operate in accordance with the us, namely different object to call the same method, the results will vary.

We know that the static keyword modifiers member variables and methods to make them the owner of the class, not the owner of the object. For example, we modify the age property of Person to be static. Look at the following example:

public class Person {
    String name;
    static int age;     // The name attribute is modified to static
    
    /* The rest of the code remains unchanged... * /
}
Copy the code

The output is as follows:

What we find is that the result is a little different, that when we assign the age property of P2, it interferes with the age property of P1. Why is that? Let’s look at them again in memory:

If you add the static keyword to the age attribute, the Person object will no longer have the age attribute. The age attribute will be assigned to the Person class. In other words, multiple Person objects will only have one age attribute. We see that age, like the toString() method, is managed by the class.

Although we have seen that static allows objects to share attributes, it is rarely used in practice and is not recommended. This makes it hard to control because it can be changed anywhere. If we want to share attributes, we usually do something else:

package cn.hz;

/ * * *@author hz
 * @version1.0 * /
public class Person {
    private static int count = 0;     // Share data
    int id;
    String name;
    int age;

    public Person(a) {
        id = ++count;
    }

    public String toString(a) {
        return "Id:" + id + ", Name:" + name + ", Age:" + age;
    }

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.name = "zs";
        p1.age = 10;
        Person p2 = new Person();
        p2.name = "ls";
        p2.age = 12; System.out.println(p1); System.out.println(p2); }}Copy the code

The output is as follows:

Id = Person; id = Person; id = Person; id = Person; id = Person; id = Person; The count attribute records the total number of Person objects created. Count is private, so it can’t be changed from outside the class.

2). Static modify member method:

Java provides static and non-static methods. A static method is a class method that can be called without creating an object. A non-static method is a method of an object that can be used only after the object has been created

Static methods cannot use the this and super keywords. Non-static methods cannot be called. Only static member variables and methods of the class to which they belong can be accessed. In the same way, static methods cannot access variables of a non-static type.

package cn.hz;

/ * * *@author hz
 * @version1.0 Static methods can only call static properties and methods, not non-static properties and methods */
public class Person {
    public static  String name;   // Static attributes
    public static void show(a){
        System.out.println("Static method");
    }
    public static void print(a){
        System.out.println("Calling static properties:"+name);           // Invoke static properties
        show();                                               // Call static methods}}Copy the code

When using static methods, note that static methods can only call static properties and methods, not non-static properties and methods.

The use of static methods, singleton pattern:

package cn.hz;

/ * * *@author hz
 * @version1.0 * Singleton mode: Lazy mode */
public class Singleton {
    // Define private static attributes
    private static Singleton instance=null;
    // Privatize the constructor
    private Singleton(a){}
    // Provide public access, because the constructor is private, so it is not allowed to create objects externally, only to call the method through the class
    public static Singleton getInstance(a){
        if(instance==null){
            instance=new Singleton();
        }
        returninstance; }}Copy the code

This is the lazy pattern in one of our design patterns in Java, the singleton pattern, which privatizes constructors, that is, does not allow external creation of objects, so how do you make objects created in a class available for external use? Define external access as static static methods, directly through the class. Static methods are called.

3). Static code blocks

Static code blocks are independent of the code blocks of member variables and functions in a class. Note: Static code blocks are executed only once. Before we look at static code blocks, let’s look at an example:

package cn.hz;

/ * * *@author hz
 * @versionDefines a Book class */
public class Book {
    public Book(String msg) { System.out.println(msg); }}Copy the code
package cn.hz;

/ * * *@author hz
 * @version1.0 * * Defines a Person class: Book object as an attribute */
public class Person {
    Book book1 = new Book("Book1 member variable initialization");
    static Book book2 = new Book("Static member book2 member variable initialization");

    public Person(String msg) {
        System.out.println(msg);
    }

    Book book3 = new Book("Book3 member variable initialization");
    static Book book4 = new Book("Static member book4 member variable initialization");

    public static void main(String[] args) {
        Person p1 = new Person("P1 initialization"); }}Copy the code

The output is as follows:

In the example above, four Book member variables are combined in the Person class, two ordinary members and two static class members. We can see that when we new a Person object, the static-modified member variable is initialized first, followed by the ordinary member, and finally by calling the Constructor of the Person class. That is, the static modified members are initialized first when the object is created, and we can also see that if there are more than one static modified members, they are initialized according to their sequential position.

In fact, static members can be initialized earlier, as shown in the following example:

package cn.hz;

/ * * *@author hz
 * @versionDefines a Book class */
public class Book {
    public Book(String msg) { System.out.println(msg); }}Copy the code
package cn.hz;

/ * * *@author hz
 * @version1.0 * * Defines a Person class: Book object as an attribute */
public class Person {
    Book book1 = new Book("Book1 member variable initialization");
    static Book book2 = new Book("Static member book2 member variable initialization");

    public Person(String msg) {
        System.out.println(msg);
    }

    Book book3 = new Book("Book3 member variable initialization");
    static Book book4 = new Book("Static member book4 member variable initialization");

    public static void funStatic(a) {
        System.out.println("FunStatic method for static modifier");
    }

    public static void main(String[] args) {
        Person.funStatic();
        System.out.println("* * * * * * * * * * * * * * * *");
        Person p1 = new Person("P1 initialization"); }}Copy the code

The output is as follows:

In the example above we can find two interesting place, the first is when we didn’t create the object, but a class to invoke methods through, although this method didn’t use to any member of the class, class member is initialized before the method call, this means that when we have to use a class for the first time, will trigger the initialization of the class members. When we initialize the class member using the class method, we do not initialize the static member again. This means that the program only needs to initialize the static member once.

When we initialize static members, we can put them in a block statement that starts with static and is wrapped in curly braces:

package cn.hz;

/ * * *@author hz
 * @versionDefines a Book class */
public class Book {
    public Book(String msg) { System.out.println(msg); }}Copy the code
package cn.hz;

/ * * *@author hz
 * @version1.0 * * Defines a Person class: Book object as an attribute */
public class Person {
    Book book1 = new Book("Book1 member variable initialization");
    static Book book2;

    static {
        book2 = new Book("Static member book2 member variable initialization");
        book4 = new Book("Static member book4 member variable initialization");
    }

    public Person(String msg) {
        System.out.println(msg);
    }

    Book book3 = new Book("Book3 member variable initialization");
    static Book book4;

    public static void funStatic(a) {
        System.out.println("FunStatic method for static modifier");
    }

    public static void main(String[] args) {
        Person.funStatic();
        System.out.println("* * * * * * * * * * * * * * * *");
        Person p1 = new Person("P1 initialization"); }}Copy the code

The output is as follows:

Through the results we found that the two results are the same, but in the code we have carried out the corresponding optimization, static block is still more practical occasions, generally used for resource initialization, for example, we can use static block initialization when we load database connection information in JDBC.

4). Static package guide:

The fourth use is probably less well known than the three above, but it’s actually simpler and more convenient when calling class methods. As an example of the “PrintHelper” example above, with a slight variation, we can use the convenience of static packets:

package cn.hz;
public class PrintHelper {
    public static void print(Object o){ System.out.println(o); }}Copy the code
import static cn.hz.PrintHelper.*;

public class App 
{
    public static void main( String[] args )
    {
        print("Hello World!"); }}Copy the code

The output is Hello Word!

The code above comes from two Java files, where PrintHelper is simple and contains a static method for printing. PrintHelper = static; PrintHelper = static; PrintHelper = static; PrintHelper = static Unlike non-static imports, static imports do not use the class name unless they conflict with the method name of the current class. The “method name” method can be used to call the class method, as if it were the class’s own method.

Conclusion:

  • Used to modify the member variable, it becomes a member of the class, so as to achieve all objects to share the member;
  • To modify a member method to a class method, use the class name. Method name, commonly used in utility classes;
  • Static block usage, which initializes multiple class members together, makes the program more orderly, in which understanding the object initialization process is very critical;
  • Static guide package usage, the method of the class directly into the current class, so that the direct use of “method name” can call the class method, more convenient.