static

When something is static, it means that the field or method is not dependent on any particular object instance. Even if we have never created an object of that class, we can call its static methods or access its static fields without the overhead of instantiating a new object.

In contrast, for normal non-static fields and methods, we must first create an object and use that object to access the field or method, because non-static fields and methods must be associated with a specific object.

Static variables and methods

class Util {
    public final int num = 100;

    public static int staticNum = 100;

    public int getAbs(int num) {
        return Math.abs(num);
    }

    public static int getSum(int a, int b) {
        Static methods cannot access non-static variables.
        System.out.println(c);
        
        Static methods cannot access non-static variables.
        getAbs(-10);
        returna + b; }}class Main {
    public static void main(String[] args) {
        // The static method is accessed through the class
        System.out.println(Util.getSum(1.2));

        // Yes, static variables are accessed through classes
        System.out.println(Util.staticNum);

        // warning that static methods are called from an instance of the class, equivalent to util.getsum (1, 2).
        // It will not be saved here, but it may cause a series of problems.
        System.out.println(new Util().getSum(1.2)); }}Copy the code

When using the static decorate a method of | variable, we call it the static methods | variable.

Static methods | variable does not belong to any object, so can’t through the this tone | variable with the proposed method can only access by the name of the class.

The class’s non-static member variables and methods cannot be accessed in a static method because they must depend on a specific object to be called.

The static block

class Test {
    static {
        System.out.println("The static block!");
    }

    public Test(a) {
        System.out.println("The constructor!"); }}public class Main {
    public static void main(String[] args) {
        /** * static block! * constructor! * constructor! * /
        new Test();
        newTest(); }}Copy the code

A static block of code is executed only once during class loading, and no subsequent class loads are executed. Therefore, initialization can be performed in a static block of code, which can greatly improve efficiency.