Nanny-level explanation of static keyword

What is the static keyword?

In Java, a static keyword is defined, which is used to modify members of a class, such as member variables, member methods, and code blocks. When a member is declared static, it is called a class member (or class attribute), not an instance member. There is only one copy of class members in memory, which is shared by all objects. Can be accessed directly through the class namewithout creating an instance of the class.

1. Sharability

When defining a class, it only describes the characteristics and behavior of a certain type of thing, and does not generate specific data. Only after an instance object of this class is created through the new keyword, the system will allocate memory space to each object to store its own data. Later, people wanted certain specific data to have only one copy in the memory, and to be shared by all instance objects in a class, so that it could be greatly reduced. Memory space usage, saving resources.
Take static variables as an example:

public class Student {<!-- -->
    static String schoolName;
    public static void main(String[] args) {<!-- -->
        Student s1 = new Student();
        Student s2 = new Student();
        Student.schoolName = "Bili University";

        System.out.println("I am" + s1.schoolName + "student");
        System.out.println("I am" + s2.schoolName + "student");
        System.out.println("I am" + Student.schoolName + "student");
    }
}

As can be seen, schoolName is a static variable that can be called directly using Student.schoolName or through Student. Instance object is called (s1 and s2 share schoolName)

1. Static variables

Static variables: Variables modified with static are called static variables (or class variables). They belong to classes rather than instances.
Modifying the value of a static member through an object will affect all other objects’ access to the static member.

class MyClass {<!-- -->
    static int staticVariable;//static variable
    int instanceVariable;//instance variable

    public static void main(String[] args) {<!-- -->
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();

        obj1.staticVariable = 10;
        System.out.println(obj2.staticVariable); // Output 10

        obj1.instanceVariable = 20;
        System.out.println(obj2.instanceVariable); // Output 0

obj2.instanceVariable = 30;
        System.out.println(obj1.instanceVariable); //Output 20

        obj1.instanceVariable = 30; //Output 30
        System.out.println(obj1.instanceVariable);
    }
}

First output: staticVariable is a static variable. Although it is referenced by obj1 and initialized to 10, the output
The value of obj2.staticVariable is also 10, so the value of this static variable is the same no matter which object is referenced.
Second output: obj2.instanceVariable is an instance variable and is not explicitly initialized. Therefore, its default value is 0.
The third output obj2.instanceVariable is initialized to 30, but the output value of obj1.instanceVariable is 20. This emphasizes the value of the instantiated object to see clearly which object it is. In citation
The fourth output: obj1.instanceVariable has been initialized to 30, so the output is 30

2. Static methods

Static method: Methods modified with static are called static methods (or class methods). Static methods can be called directly through the class name, without creating an instance of the class. It is worth noting that static methods can only access static variables and call other static methods, but cannot access non-static instance variables and instance methods.
There is no static modified speak method in line 2, and idea directly reports an error. This shows that static methods can only call other static methods and cannot access non-static instance methods. Here is an example of correct code:

class Person {<!-- -->
    public static void speak() {<!-- --> //Define static method
        System.out.println("Hello!");
    }
}
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Person.speak();//The static method is called in the form of "class name.method"
        Person p = new Person();
        p.speak();//The static method is called in the form of "instance object name.method"
    }
}

Both successfully output “Hello!” This can also show that static members can be shared by all instantiated objects.

3. Static code block

Static code block: A block of code defined using the static keyword. It is executed when the class is loaded and is used to initialize static variables or perform other static operations. The static code block will only be executed once and before the static variables are initialized during class loading.

The syntax of a static code block is as follows:

static {<!-- -->
    //Code in static code block
}


Static code blocks are executed when the class is loaded and will only be executed once. The constructor method is executed every time a new object of the class is created.

Specifically:

  1. Static code block: Static code block is executed as the class is loaded and will only be executed once. No matter how many objects are created, static code blocks are executed only once.
  2. Constructor method: The constructor method is executed every time an object of a class is created. If you create 10 objects, the constructor will be called 10 times.

It should be noted that the execution order of static code blocks and construction methods is: static code blocks first, then construction methods. If there are multiple static code blocks, these static code blocks are executed in the order they appear in the code. Similarly, if there are multiple constructors, these constructors are executed in the order they appear in the code.

4. Static inner classes

Static inner class: An inner class modified with static is called a static inner class. Static inner classes have nothing to do with instances of the outer class and can be accessed directly through the outer class name.

The following introduces some differences and characteristics between static inner classes and ordinary inner classes (non-static inner classes).
1. Definition method: The definition method of static inner class is to use the static keyword to modify a class inside the outer class. For example:

public class OuterClass {<!-- -->
    //Members and methods of external classes

    public static class StaticInnerClass {<!-- -->
        // Members and methods of static inner classes
    }
}

2. Independence: Static inner classes are static members of the outer class and have nothing to do with instances of the outer class. It can exist independently without relying on instances of external classes. Therefore, a static inner class can be accessed directly through the class name of the outer class.

3. Access permissions: Static inner classes can have public, private, protected or default (package level) access permissions, just like ordinary classes. Its access rights are not restricted by those of external classes.

4. Access external classes: Static inner classes can directly access static members of external classes, including static variables and static methods. If you need to access non-static members of an external class, you need to access them through an object instance.

5. Instantiation: To instantiate a static inner class, an instance of the outer class is not required. Objects can be created directly using the class name of a static inner class. For example:

OuterClass.StaticInnerClass inner = new OuterClass.StaticInnerClass();

6. Life cycle: The life cycle of static inner classes is independent of external classes. Even if the instance of the outer class is destroyed, the object of the static inner class can still exist.

To summarize, static inner classes are useful in certain situations, especially when the inner class does not need to access instance variables or methods of the outer class. It provides a way to organize and encapsulate related functionality and can be accessed directly through the class name of the external class.

The above is my explanation of the static keyword. I hope it can be helpful to everyone! ! !