Java Note--static

Source: Internet
Author: User

1.static modifier variables

 Public class MyClass {    staticint i = 4;}

Where the static modifier variable, which indicates that the variable i belongs to the MyClass class, all objects share a variable, it is recommended to use the class name to access the static variable (1. The static design structure is emphasized; 2. Provides an opportunity for compiler optimizations);

Do not use private to modify the static variable, otherwise it cannot be accessed with the class name.

2.static Modification Method

 Public class incrementable {    staticvoid  increment () {        myclass.c+ +;    }}

The static modifier method and the modifier variable are the same, and the static method can only access static member variables and methods of this class, and cannot access non-static variables and methods;

The main function is defined as static to provide a portal for the program.

3.stack Modified Class

Static can only decorate inner classes

 Public class MyClass {    staticclass  sclass {        publicvoid  Hello () {                    }    }}

Sometimes it is possible to write the main function to an inner class (static Class) without having to write a main method for each file.

4.static Block

 Public class MyClass {    static  {        = 1;    }     Static int A;}

Static blocks are executed only once when the class is loaded, and are typically used to initialize both statically variable and static methods.

Java Note--static

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.