Java keyword—static

1 Introduction of the static keyword

​ When we write a class, we actually describe the properties and behavior of the class, and there is no substantial object. Only through the new keyword can the object be generated. At this time, the system will allocate memory space to the object, and its method can be External call.

​ But sometimes we hope that no matter how many objects are generated , there is only one copy of certain specific data in the memory space . For example, all Chinese people share the Chinese name of this country, do not have to every Chinese person in the instance of an object is assigned a variable representing the country name for, then you can use staticthe keyword

2 Use of static

static: static

Structures that can be modified: attributes, methods, code blocks, internal classes (here we first discuss the modification of attributes and methods)

No matter what structure is modified, the structure will be loaded with the loading of the class

2.1 Use static to modify attributes

Attributes can be divided into static attributes (class variables) and non-static attributes (instance attributes) according to whether there is static modification

Non-static variables : When we create a class of multiple objects, each object each have a class of non-static properties change when one of the objects of non-static properties, will not affect the rest of the non-static objects Attributes

Static variables : When we create a class of multiple objects, each object sharing non-static properties of the class, when you modify a static variable through an object, that could cause other objects to call the static variable is modified

Description : ①: Static variables with the load and load class , you can call the class static variable.

​ ②: The loading of static variables is earlier than the creation of objects

​ ③: Since the class is only loaded once, there is only one static variable in the memory, and there is a static field in the method area

2.2 Use static modification method

①: Load with the loading of the class

②: Static methods can only call static properties and static methods

​ Non-static methods can call both static properties, non-static properties, static methods, and non-static methods

​ This can be considered from the perspective of the life cycle, first is the class is loaded into the method area, and then the object is created

③: In the static method, this or super keywords cannot be used

class Person{
    
    
    
    String name;
    int age;
    static String country = "中国";	//将国家设置为静态变量
    
    public void eat(){
    
    
        //非静态方法可以调用静态属性,静态方法和非静态属性,非静态方法
    }
    
    public static void sleep(){
    
    
        //静态方法只能调用静态属性,静态方法,不能调用非静态属性,非静态方法
    }
}

Guess you like

Origin blog.csdn.net/weixin_45321793/article/details/109366289