Java study notes-static usage

Static is the most basic keyword usage when learning java, but it has been useless for a long time, and I forgot the usage, mark it

 

1. Features

The method or variable modified by the static keyword does not need to depend on the object for access, as long as the class is loaded, it can be accessed through the class name.   

Static can be used to modify the member methods of the class, the member variables of the class, and you can write static code blocks to optimize program performance.

 

2. Usage

1. Static method

Explanation: Non-static member variables and non-static member methods of the class cannot be accessed in static methods, because non-static member methods/variables must rely on specific objects to be able to be called.

But in non-static methods, you can call static methods and static variables.

public class Test {

    public String name="xxx";
    public static String hobby="play";

    public static void test_static(){
        System.out.println(hobby);
        //静态方法中不能访问非静态变量
        System.out.println(name);

    }
}

 

2. Static variables

Static variables are shared by all objects, there is only one copy in memory, and it will be initialized if and only when the class is first loaded . Non-static variables are owned by the object and are initialized when the object is created. There are multiple copies, and the copies owned by each object do not affect each other.

 

3. Static class

If a class is to be declared as static, there is only one case, that is, the static inner class.

1. Static inner classes are the same as static methods. They can only access static member variables and methods, and cannot access non-static methods and properties, but ordinary inner classes can access member variables and methods of any outer class.

2. Static inner classes can declare ordinary member variables and methods, while ordinary inner classes cannot declare static member variables and methods.

3. Static inner classes can be initialized separately

I searched a circle of information and said that static classes are generally used to extend methods, and how to extend them, we still need to look at it again.

 

4. Static code block

Static code blocks can be placed anywhere in the code to optimize performance, and will only be executed once when the class is loaded

public class Test {

    static{
        System.out.println("test");
        System.out.println("static");
    }
}

 

 

Guess you like

Origin blog.csdn.net/mumuwang1234/article/details/115181525