Java Review Road 4

Source: Internet
Author: User

Static use in Java

1. Static variables (class variables).

2. Static methods (class methods). In fact, the main method we've been writing about is static methods.

Need to note:

1 static members can be called directly in a static method, but not non-static members directly.

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.

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

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

4. Static initialization block

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.

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.

Java Review Road 4

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.