The static keyword modifies member variables and methods?

In object-oriented, there are concepts of class and object. We defined some member variables in the class, such as name, age, sex, and found that these member variables exist in every object (because every object can be accessed).

And like name, age, sex are indeed attributes that every student object should have, and should belong to each object.

Therefore, members (variables and methods) in Java are attributes, and Java is distinguished by the static keyword. The static keyword is very important in Java development, and it is critical to understand object-oriented. static means static. static can modify member variables or modify methods.

A static modified member variable indicates that the member variable belongs to the class. This member variable is called a class variable or a static member variable. It can be accessed directly by class name. Because there is only one class, there is only one copy of static member variables in the memory area. All objects can share this variable.

For example, now we need to define all the student classes of Chuanzhi, then the school attributes of the objects of these student classes should be "Chuanzhi". At this time, we can define this property as a static member variable modified by static. The format of a static member variable modified by static is as follows:

修饰符 static 数据类型 变量名 = 初始值;

For example, define the attribute "Chuanzhi" as a static member variable modified by static, the format is as follows:

public class Student {
    public static String schoolName = "传智播客"; // 属于类,只有一份。
    // .....
}

Access to static member variables can be named in the format: class name.static variable.

public static void  main(String[] args){
    System.out.println(Student.schoolName); // 传智播客
    Student.schoolName = "黑马程序员";
    System.out.println(Student.schoolName); // 黑马程序员
}

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130470771