Static variables and static methods in java

Static variables used by static in Java

Everyone knows that we can create multiple objects of this class based on a class, each object has its own members, independent of each other. However, at certain times, we prefer that all objects of this class share the same member. This is the time for static to show its talent! !

Members modified by static in Java are called static members or class members. It belongs to the entire class, not an object, that is shared by all objects of the class. Static members can be accessed directly using the class name or using the object name. Of course, in view of the special nature of his role, it is more recommended to use the class name to visit ~~

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

In this section, we first understand static variables.

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

operation result:

Pay attention: 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 before resource recovery! ~~

Static methods used by static in Java

As with static variables, we can also use static decoration 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 static methods, you can directly call static members of the same kind, but you cannot directly call non-static members. 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 the ordinary member method, you can directly access non-static variables and static variables of the same type , as follows:

3.  Non-static methods cannot be called directly in static methods. You need to access non-static methods through objects. Such as:

Published 8 original articles · Likes2 · Visits 485

Guess you like

Origin blog.csdn.net/qq_42003546/article/details/102811919