Static variables and static methods used by static in Java

 

Members modified by static in Java are called static members or class members. It belongs to the entire class, not an object, that is, it is shared by all objects of the class. Static members can be accessed directly using the class name, or they can be accessed using the object name. The member variables and member methods modified by static are independent of any objects of this class. In other words, it does not depend on a specific instance of the class and is shared by all instances of the class.

Of course, in view of the particularity of his role, it is more recommended to use the class name to visit~~

Use static to modify variables, methods, and code blocks.

For example, we define a static variable hobby in the class, the operation code is as follows:

operation result:

Pay attention to: static members belong to the entire class. When the system uses the class for the first time, it will allocate memory space for it until the class is unloaded. ~~

Like static variables, we can also use static modification methods, called static methods or class methods. In fact, the main method we have been writing before is a static method. The use of static methods such as:

operation result:

requires attention:

1. In a  static method, static members of the same class can be directly called, but non-static members cannot be called directly. Such as:

If you want to call a non-static variable in a static method, you can create an object of the class, and then access the non-static variable through the object . Such as:

2.  In ordinary member methods, you can directly access non-static variables and static variables of the same kind , as shown below:

3.  Non-static methods cannot be called directly in static methods, and non-static methods need to be accessed through objects. Such as:

Guess you like

Origin blog.csdn.net/sang_12345/article/details/81173793