Static use in Java

Source: Internet
Author: User

Static keyword

As we all know, we can create multiple objects of this class based on a class, each with its own members and independent of each other. At some point, however, we would prefer all objects of the class to share the same member. This is the time for static!
Static represents the meaning of "global" or "static", which modifies member variables and member methods, and can also form statically static blocks of code, but there is no concept of global variables in the Java language.
member variables and member methods that are modified by static are independent of any object of the class. That is, it does not depend on class-specific instances and is shared by all instances of the class. As long as this class is loaded, the Java virtual machine can find them based on the class name in the method area of the run-time data area. Therefore, a static object can be accessed before any of its objects are created, without referencing any objects.
Use static to modify variables, methods, and blocks of code.

Static variables used in Java

There are two types of class member variables that can be classified according to whether they are static: A variable that is statically modified, called a static variable or a class variable, and a variable that is not modified by static, called an instance variable.
The difference between the two is:
For static variables in memory only one copy (save memory), the JVM allocates only one memory at a time, in the process of loading classes to complete the memory allocation of static variables, the use of the class name directly accessible (convenient), of course, can also be accessed through the object (but this is not recommended);
For instance variables, when an instance is not created, the instance variable is allocated one memory, and the instance variable can have multiple copies in memory without compromising (flexibility).
For example, we define a static variable hobby in the class, and the operation code is as follows:

Operation Result:

Let's look at an example:
A HelloWorld class is defined in the editor, a static variable className is defined in the class, and the class name is saved. A static variable is called in the main method to output class information.
The code is as follows:

publicclass HelloWorld {    // 定义静态变量,保存班级名称       static"JAVA开发一班";    publicstaticvoidmain(String[] args) {        // 访问静态变量,输出班级名称        System.out.println(HelloWorld.className);    }}
Static methods for using static in Java

Static methods can be called directly from the class name, and any instance can also be called, so a static method cannot use the This and Super keywords, and cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static). Only static member variables and member methods of the owning class can be accessed. Because instance members are associated with specific objects! This need to understand, to understand the truth, not memory! Because the static method is independent of any instance, the static method must be implemented, not abstract.
Use of static methods:

Operation Result:

need to note:
    • 1. Static methods can call static members directly in the same class, but not non-static members directly. Such as:

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

      * *. In a normal member method, you can directly access a class of non-static variables and static variables, as follows:
    • 3. Non-static methods cannot be called directly in static methods, and non-static methods need to be accessed through objects. Such as:

Finally, let's look at one more example:

 Public classHelloWorld {//define static variable Score1    Static intScore1 = the;//define static variable Score2    Static intScore2 = the;//define static method sum, calculate total score, and return total score     Public Static int sum() {returnScore1+score2; } Public Static void Main(string[] args) {//Call the static method sum and receive the return value        intAllscore =sum (); System. out. println ("Total score:"+ Allscore); }}

Output:

总分:178
Static initialization block used in Java

A static block of code is also called a code block, which is an independent block of static blocks in a class that is separate from a class member, can have more than one position, it is not in any method body, and the JVM executes these static blocks of code when the class is loaded, and if there are multiple static blocks of code, The JVM executes them sequentially in the order in which they appear in the class, and each code block is executed only once. Static initialization blocks can only assign values to static variables, and cannot initialize normal member variables.

Operation Result:

by outputting The result, we can see that the static initialization block is executed first when the program is run, then the normal initialization block is executed, and the construction method is finally executed. Because static initialization blocks are only executed once when the class is loaded, static initialization blocks are not executed when the object Hello2 is created again.

Practice

The variables are initialized by constructing methods, initialization blocks, and static initialization blocks, respectively:

 Public classHelloWorld {String name;//Declare variable nameString sex;//DECLARE variable sex    Static intAge//Declare static variable age    //Construction method     Public HelloWorld() {System. out. println ("Initialize name by construction method"); Name ="Tom"; }//Initialization block{System. out. println ("Initialize sex by initializing blocks "); Sex ="Male"; }//Static initialization block    Static{System. out. println ("Initialize age by static initialization block"); Age = -; } Public void Show() {System. out. println ("Name:"+ name +", Gender:"+ Sex +", Age:"+ age); } Public Static void Main(string[] args) {//Create ObjectsHelloWorld Hello =NewHelloWorld ();//Call the object's Show methodHello.show (); }}

Output Result:

通过静态初始化块初始化age通过初始化块初始化sex通过构造方法初始化name姓名:tom,性别:男,年龄:20

Static use in Java

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.