How to use Java static (6)

Source: Internet
Author: User

Static variables used in Java

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!!

Members in Java that are decorated statically are called static members or class members. It belongs to the whole class, not to an object,

is shared by all objects of the class. Static members can be accessed directly by using the class name or by using the object name.

Of course, given the particularity of his role, it is more recommended to access the class name ~ ~

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

Here, let's get to know the static variables first.

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

Operation Result:

Note: Static members belong to the entire class, and when the system first uses the class, it allocates memory space until the class is unloaded for resource recycling! ~~

Static methods for using static in Java

As with static variables, we can also use the static modification method, called a static method or a class method.

In fact, the main method we've been writing about is static methods. The use of static methods such as:

Operation Result:

Need to note:

1 static members can be called directly in a static method, 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:

2, in the ordinary member method, you can directly access the same kind of non-static variables and static variables, as follows:

3, static methods can not directly invoke non-static methods, you need to access the non-static method through the object. Such as:

Give me a chestnut:

1  Public classHelloWorld {2     3     //defining static Variables Score14     Static intScore1 = 86;5     //defining static variables Score26       Static     intScore2 = 92; 7 8     //defines the static method sum, calculates the score score, and returns the total score9      Public Static  intsum () {Ten        One       returnscore2+Score1; A        -     } -  the      Public Static voidMain (string[] args) { -          -         //call the static method sum and receive the return value -         intAllscore =sum (); +          -SYSTEM.OUT.PRINTLN ("Total score:" +allscore); +     } A}

Static initialization block used in Java

In Java, data can be assigned by initializing blocks. Such as:

In the declaration of a class, you can include multiple initialization blocks, which are executed sequentially when you create an instance of the class. If you initialize a block with the static adornment, it is called a static initialization block.

It is important to note that static initialization blocks are only executed when the class is loaded and only once, while static initialization blocks can only assign values to static variables and cannot initialize normal member variables.

Let's look at a piece of code:

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.

Give me a chestnut:

1  Public classHelloWorld {2     3String name;//declaring variable name4String sex;//Declaring variables Sex5     Static intAge//declaring a static variable age6     7     //Construction Method8      PublicHelloWorld () {9SYSTEM.OUT.PRINTLN ("Initialize name by construction method");TenName = "Tom"; One     } A      -     //Initialize block -     {  theSYSTEM.OUT.PRINTLN ("Initialize sex by initialization block"); -Sex = "male"; -     } -      +     //Static initialization blocks -         Static    {  +SYSTEM.OUT.PRINTLN ("Initialize age by static initialization block"); AAge = 20; at     } -      -      Public voidShow () { -System.out.println ("Name:" + name + ", Gender:" + Sex + ", Age:" +Age ); -     } -      in      Public Static voidMain (string[] args) { -          to         //Creating Objects +HelloWorld Hello =NewHelloWorld (); -         //call the Show method of an object the hello.show (); *          $     }Panax Notoginseng } - /* the initializing the age with static initialization blocks + Initialize the sex by initializing the block A Initialize name by constructing method the name: Tom, Sex: Male, Age: + */

How to use Java static (6)

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.