Java Keywords (iii)--static

Source: Internet
Author: User
Tags modifier java keywords

We say that Java is an object-oriented programming language, and the object is to put the data and the operation of the data together, as an interdependent whole, to the same kind of object abstraction of its commonality, is the class in Java, we can use the class to describe the world of all things, can also say that all objects. But here's a special thing--static, it doesn't belong to the object, so why?

Static is a keyword in Java that can be used to modify member variables, modify member methods, construct static code blocks, implement static leader, and implement static inner classes, which we'll describe separately.

1. Modify member variables

Using the static modifier member variable can be said to be the most common function of the keyword, usually the static decoration of the member variable is called a class member or a static member, then what is the difference between a statically member and a non-static member without static decoration?

Let's take a look at the in-memory construction of member variables without static modifiers.

1  PackageCom.ys.bean;2 3 /**4 * Create by Ysocean5  */6  Public classPerson {7     PrivateString name;8     PrivateInteger age;9 Ten      PublicPerson (String name, Integer age) { One          This. Name =name; A          This. Age =Age ; -     } -  the @Override -      PublicString toString () { -         return"Person{" + -"Name=" + name + ' \ ' + +", age=" + Age + -‘}‘; +     } A     //get and Set methods omitted at}
View Code

First, we create an entity class person with two properties name and age, all of which are normal member variables (not decorated with the static keyword), and then we create two objects through its construction method:

1 New Person ("Tom", +); 2 New Person ("Marry"); 3 System.out.println (p1.tostring ()); // person{name= ' Tom ', age=21} 4 System.out.println (p2.tostring ()); // person{name= ' Marry ', age=20}

The storage structure of these two objects in memory is as follows:

  

It is known that the two objects we created P1 and P2 are stored in the heap, but their reference addresses are stored in the stack, and the two variables of the two objects are independent of each other, and we modify the property values of any one object without changing the property value of the other object.

Here we change the age property in the person class to be decorated with the static keyword:

1  PackageCom.ys.bean;2 3 /**4 * Create by Ysocean5  */6  Public classPerson {7     PrivateString name;8     Private StaticInteger age;9 Ten      PublicPerson (String name, Integer age) { One          This. Name =name; A          This. Age =Age ; -     } -  the @Override -      PublicString toString () { -         return"Person{" + -"Name=" + name + ' \ ' + +", age=" + Age + -‘}‘; +     } A     //get and Set methods omitted at  -}
View Code

Similarly, we will create the P1 and P2 two objects as above, and print the two objects to see what is the difference between the printed one and the above?

1 New Person ("Tom", +); 2 New Person ("Marry"); 3 System.out.println (p1.tostring ()); // person{name= ' Tom ', age=20} 4 System.out.println (p2.tostring ()); // person{name= ' Marry ', age=20}

We found that the third line of code prints the P1 object with the age property changed to 20, which is why?

  

This is because in the memory construct of the JVM, a memory space is created in the heap that is dedicated to storing the static modified member variable, called the quiescent store, no matter how many objects we create, and only one copy of the member variable with static decoration is stored in the static store. So the value of the static variable is the value of the static variable that was set when the object was last created, that is, because P1 set age = 21, then created the P2 object, and P2 changed age to 20, the age property value of the static store is also modified to 20.

PS: Before JDK1.8, the static storage area is stored in the method area, and the method area is not a heap, after JDK1.8, the method area is eliminated, the static storage in the method area is changed to storage in the heap.

  Summary: Static modified variables are shared by all objects and have only one copy in memory. Because it is independent of the object, we can directly invoke the static variable by the way of the class name. The corresponding non-static variable is owned by the object, how many objects have non-static variables, and the copies owned by each object are unaffected.

2. Modifying member Methods

The same is true with the static keyword to decorate the member method, which we can call directly through the class name. static method name () instead of creating the object.

1  Public classPerson {2     PrivateString name;3     Private StaticInteger age;4 5      Public Static voidPrintclassname () {6System.out.println ("Com.ys.bean.Person");7     }8      PublicPerson (String name, Integer age) {9          This. Name =name;Ten          This. Age =Age ; One     } A  - @Override -      PublicString toString () { the         return"Person{" + -"Name=" + name + ' \ ' + -", age=" + Age + -‘}‘; +     } -     //get and Set methods omitted +  A}
View Code

Call a static method:

1 person.printclassname (); // Com.ys.bean.Person
3. Static code block

Static code blocks, called static blocks of code, can be placed anywhere in the class (and member variable member methods are equal, not in methods), and a class can have multiple static blocks of code that load static blocks of code when the class first loads into memory. It is loaded in the order of the declared static blocks of code and is loaded only once, with precedence over various code blocks and constructors.

The difference between static blocks of code, building blocks, constructors, and ordinary blocks of code can be found in my blog post.

1  Public class Codeblock {2     Static {3         System.out.println ("Static code block"); 4     }5 }

Since static code blocks are only loaded once when the class loads into memory, we can use static blocks of code to optimize program performance, such as when a larger configuration file needs to be loaded when the object is created, and in order to save memory, we can put the load time of the configuration file into a static block of code. Then, no matter how many objects are created, the configuration file is loaded only once.

4, Static Guide package

Using static to modify member variables, member methods, and static code blocks is the most commonly used three functions, static guide package is a new feature after JDK1.5, with the import static package name in place of the traditional import package name mode. So what's the use?

For example, we create an array, and then use the Sort method of the Arrays tool class that the JDK comes with to sort the arrays:

1  Packagecom.ys.test;2 3 Importjava.util.Arrays;4 /**5 * Create by Ysocean6  */7  Public classStatictest {8 9      Public Static voidMain (string[] args) {Ten         int[] Arrays = {3,4,2,8,1,9}; One Arrays.sort (Arrays); A     } -}

As we can see, when invoking the sort method, the import java.util.Arrays is required for the guide package, then it becomes a static guide.

1  Packagecom.ys.test;2 3 Import Staticjava.util.arrays.*;4 /**5 * Create by Ysocean6  */7  Public classStatictest {8 9      Public Static voidMain (string[] args) {Ten         int[] Arrays = {3,4,2,8,1,9}; One sort (arrays); A     } -}

We can see that the import java.util.Arrays of the third line of code becomes the import static java.util.arrays.*, meaning that all static methods in the Arrays class are imported, and of course you can change the * to a method name Into this method, we can call this method without the class name, directly from the method name (the 11th line of code).

Static guides only reduce the amount of code written by the programmer, there is no improvement in performance (and no performance degradation, Java Core Technology 10th Edition Volume 1 148th page 4.7.1 Chapter class import is introduced), but will reduce the readability of the code, so the actual use of the need to trade off.

5. Static internal class

First we need to know what an inner class is, a class defined inside a class called an inner class, a class containing an inner class called an outer class, and an inner class with a static modifier is what we call a statically inner class.

The benefit of defining an inner class is that the external class can access all the methods and properties of the inner class, including private methods and private properties.

To access the ordinary inner class, we need to create an object of the outer class first, and then create an instance of the inner class from the external class name.

  1  package   Com.ys.bean;    3  /**   4   * Create by Hadoop   5  */  6  public  class   Outclass {  7   public  class   innerclass{  9  10   11  }

1  New Outerclass (); 2  * Outerclass.innerclass in = oc.new innerclass ();

To access the static inner class, we do not need to create an object of the outer class and can create an instance directly from the external class name.

1  PackageCom.ys.bean;2 3 /**4 * Create by Hadoop5  */6  Public classOutclass {7 8      Public Static classinnerclass{9 Ten     } One}

1 New Outerclass.staticinnerclass ();
6. Frequently Asked Questions

  Can ① and static variables exist in common methods?

Yes. Obviously, the ordinary method must be called through the object, the static variable can be called directly through the class name, let alone through the object to call, so it can exist in the ordinary method.

  ②, static methods can exist ordinary variables?

No. Because static methods can be directly called directly through the class name, without creating an object, a normal variable must be called through an object. The normal variable is then placed in a static method, and an error occurs when the static method is called directly through the class. So I can't.

  ③, static code blocks can be placed in the method body?

No. First, we want to make clear that static code blocks are automatically run when the class loads.

The normal method requires us to create the object and then call the method by hand, and the static code block cannot be declared in the normal method.

What about static methods that are modified with static? It's also not possible. Because static methods also require that we manually call through the class name, rather than running it directly when the class is loaded.

This means that static code blocks can be executed automatically, regardless of whether the normal or static methods need to be executed manually.

  ④, static Guide package consumes more performance than normal guide package?

No. Static guides are actually processed by the compiler during compilation, converting them into the form of a normal on-demand guide, so that performance is not affected during the run of the program.

  Can ⑤ and static be used to modify local variables?

No. The static keyword cannot be used to modify a local variable, either in a normal method or in a static method, which is the Java rule. It can also be understood that the declaration period of a local variable ends with the end of the method, because the static modified variable is global and not related to the object, and if static modifies the local variable to cause an understanding conflict, Java specifies that the static keyword cannot be used to modify the local variable.

Java Keywords (iii)--static

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.