In the Java keyword,static and final are two of the keywords we have to master. Unlike other keywords, they are used in a variety of ways, and can improve the performance of the program and optimize the structure of the program in a certain environment. Let's look at the static keyword and its usage first.
Static keyword 1. Modifying member variables
In our usual use, the most common function of static is to modify the properties and methods of the class, so that they become the members of the class properties and methods, we usually use static modified members are called Class members or static members, this sentence is very strange, in fact, this is relative to the object's properties and methods. Take a look at the following example: (no program is too bloated, temporarily regardless of access control)
Public classPerson {String name; intAge ; PublicString toString () {return"Name:" + name + ", Age:" +Age ; } Public Static voidMain (string[] args) {person P1=NewPerson (); P1.name= "Zhangsan"; P1.age= 10; Person P2=NewPerson (); P2.name= "Lisi"; P2.age= 12; System.out.println (p1); System.out.println (p2); } /**Output * Name:zhangsan, Age:10 * name:lisi, Age:12*///~}
We are familiar with the above code, each object constructed according to the person is independent, save has its own independent member variables, do not affect each other, their in-memory schematic is as follows:
As you can see, the objects referenced by the P1 and P2 two variables are stored in different addresses in the in-memory heap area, so they do not interfere with each other. But in fact, in this, we omit some important information, I believe you will also think that the object's member properties are here, by each object to save themselves, then their method? In fact, no matter how many objects a class creates, their methods are the same:
As we can see from the above figure, the method of the two person object is actually pointing to the same method definition. This method is defined as an invariant area in memory (divided by the JVM), which we temporarily call a static storage area. This piece of storage not only stores the definition of the method, but actually, from a larger point of view, it holds the definitions of the various classes, and when we build the object through new, the object is created according to the definition of the class defined here. Multiple objects will only correspond to the same method, here is a convincing reason, that is, regardless of how many objects, their methods are always the same, although the final output will be different, but the method will always follow the results we expected to operate, that is, different objects to invoke the same method, the results will vary.
We know that the Static keyword can modify member variables and methods to make them belong to the class, not the object, for example, if we decorate the age property of the person with static, what will the result be? Take a look at the following example:
Public class Person { String name; Static int Age ; /* */ /**Output * Name:zhangsan, age:12 * Name:lisi, Age:12 */// ~}
We find that the result has changed a bit, and when assigning a value to the age property of P2, it interferes with the P1--which is why? We're still looking at their in-memory schematic:
We found that after adding the static keyword to the age attribute, the person object would no longer have the age property, and the age attribute would be uniformly assigned to the person class to manage, that is, multiple person objects would only correspond to an age property. If an object changes the Age property, the other objects are affected. We see that at this time the Age and ToString () methods are all managed by the class.
Although we see static to allow objects to share properties, we rarely use them in practice, and we don't recommend it. Because it makes this property difficult to control, it can be changed everywhere. If we want to share attributes, we will generally use other methods:
Public classPerson {Private Static intCount = 0; intID; String name; intAge ; PublicPerson () {ID= ++count; } PublicString toString () {return"ID:" + ID + ", Name:" + name + ", Age:" +Age ; } Public Static voidMain (string[] args) {person P1=NewPerson (); P1.name= "Zhangsan"; P1.age= 10; Person P2=NewPerson (); P2.name= "Lisi"; P2.age= 12; System.out.println (p1); System.out.println (p2); } /**Output * id:1, Name:zhangsan, Age:10 * id:2, Name:lisi, Age:12*///~}
The code above has the effect of creating a unique ID for the person's object and the total number of records, where count is decorated by static and is a member property of the person class, and each time a person object is created, the property is added 1 and then assigned to the object's ID property, so that The Count property records the total number of person objects created, and because Count uses the private adornment, it cannot be arbitrarily changed from outside the class.
2. Modify Member Methods
Another function of static is to modify the member method. The modified member method has little variation over the storage of the data compared to the modified member property, as we can see from the above that the method is stored in the definition of the class. The static modifier member method has the greatest effect of using the " class name. Method Name " method to avoid the tedious and resource consumption of the new object first, and we may often see it used in the Help class:
Public class Printhelper { publicstaticvoid print (Object o) { System.out.println (o); } Public Static void Main (string[] args) { printhelper.print ("Hello World");} }
The above is an example (not very practical now), but we can see its role, so that the static modified method becomes the method of the class, so that the use of " class name, method name " Way can be easily used, Equivalent to defining a global function (as long as you import the package that contains the class). But it also has limitations, a static decorated class that cannot use non-static decorated member variables and methods, which is well understood, because the static modification method belongs to the class, and if you go directly to using the object's member variables, it will be overwhelmed (I don't know which object's properties to use).
3. Static block
When explaining the third use of the static keyword, it is necessary to re-comb the initialization of an object. Take the following code as an example:
PackageCom.dotgua.study;classbook{ PublicBook (String msg) {System.out.println (msg); }} Public classPerson {book Book1=NewBook ("BOOK1 member variable Initialization"); StaticBook Book2 =NewBook ("Static member BOOK2 member variable Initialization"); PublicPerson (String msg) {System.out.println (msg); } Book Book3=NewBook ("BOOK3 member variable Initialization"); StaticBook BOOK4 =NewBook ("Static member BOOK4 member variable Initialization"); Public Static voidMain (string[] args) {person P1=NewPerson ("P1 initialization"); } /**Output * Static member BOOK2 member variable initialization * Static member BOOK4 member variable initialization * BOOK1 member variable initialization * BOOK3 member variable initialization * P1 initialization *///~}
In the above example, the person class is composed of four book member variables, two are ordinary members, and two are static decorated class members. As we can see, when we new a person object, the static decorated member variable is initialized first, then the normal member, and finally the constructor method of the person class is initialized. That is, when the object is created, the static decorated member is initialized first, and we can see that if there are more than one static decorated member, it will be initialized according to their position.
In fact, the initialization of a static decorated member can be done earlier, see the following example:
classbook{ PublicBook (String msg) {System.out.println (msg); }} Public classPerson {book Book1=NewBook ("BOOK1 member variable Initialization"); StaticBook Book2 =NewBook ("Static member BOOK2 member variable Initialization"); PublicPerson (String msg) {System.out.println (msg); } Book Book3=NewBook ("BOOK3 member variable Initialization"); StaticBook BOOK4 =NewBook ("Static member BOOK4 member variable Initialization"); Public Static voidfunstatic () {System.out.println ("Static modified Funstatic method"); } Public Static voidMain (string[] args) {person.funstatic (); System.out.println ("****************"); Person P1=NewPerson ("P1 initialization"); } /**Output * Static member BOOK2 member variable initialization * Static member BOOK4 member variable initialization * Static modified Funstatic method * *************** * bo OK1 member Variable initialization * BOOK3 member variable initialization * P1 initialization*///~}
In the above example we can find two interesting places, the first is when we do not create the object, but through the class to invoke the class method, although the method does not use any of the class Members, class members or before the method call initialization, which means that when we first go to use a class, The member initialization of the class is triggered. The second is that when we use the class method, after initializing the members of the class, and then new to the object of the class, the static decorated class member is not initialized again, which means that the static decorated class member, in the process of running the program, only need to initialize once, and will not be initialized more than once.
After reviewing the initialization of the object, it is very simple to look at the third function of static, that is, when we initialize the members of the static modifier, we can place them uniformly in a block statement that begins with a static, wrapped in curly braces:
classbook{ PublicBook (String msg) {System.out.println (msg); }} Public classPerson {book Book1=NewBook ("BOOK1 member variable Initialization"); StaticBook Book2; Static{Book2=NewBook ("Static member BOOK2 member variable Initialization"); Book4=NewBook ("Static member BOOK4 member variable Initialization"); } PublicPerson (String msg) {System.out.println (msg); } Book Book3=NewBook ("BOOK3 member variable Initialization"); StaticBook Book4; Public Static voidfunstatic () {System.out.println ("Static modified Funstatic method"); } Public Static voidMain (string[] args) {person.funstatic (); System.out.println ("****************"); Person P1=NewPerson ("P1 initialization"); } /**Output * Static member BOOK2 member variable initialization * Static member BOOK4 member variable initialization * Static modified Funstatic method * *************** * bo OK1 member Variable initialization * BOOK3 member variable initialization * P1 initialization*///~}
We will make a slight change to the previous example, and we can see that the result is not two.
4. Static Guide Package
Compared to the three uses above, the fourth use may be less, but in fact it is very simple, and it is more convenient to call the class method. Take the example of "Printhelper" above, and make a slight change, and you can use the static guide to give us the convenience:
/* Printhelper.java file */ package Com.dotgua.study; public class Printhelper { public static void print (Object o) {syste M.out.println (o); }}
/* App.java file */
import static Com.dotgua.study.printhelper.* public class App { public static void main (string[] args) {print ( "Hello world!" /** output * Hello world! */// ~ }
The code above comes from two Java files, where the Printhelper is simple and contains a static method for printing. In the App.java file, we first import the Printhelper class, where we use the static keyword when we import it, and at the end of the introduction class are added ". *", Its purpose is to import all the class methods in the Printhelper class directly. Unlike a non-static import, with the static import package, without a conflict with the method name of the current class, you do not need to use the " class name. Method Name" method to invoke the class method, directly using the " method name " To invoke the class method, It is as if it were the same as the class's own method.
Summarize
Static is a very important keyword in Java, and its usage is very rich, there are four main ways to use it:
- Used to modify a member variable to become a member of a class, thus realizing the sharing of all objects with that member;
- Used to modify a member method and make it a class method, which can be called directly using the "class name. Method Name" , which is commonly used in tool classes;
- Static block usage, the initialization of multiple class members, makes the program more regular, in which the initialization process of understanding objects is very critical;
- Static Guide Package usage, the method of the class is imported directly into the current class, thus directly using the "method name" to invoke the class method, more convenient.
[Four ways to use the Java]static keyword