The Static keyword for Java

Source: Internet
Author: User

1. Objects that can be decorated are: variables, methods, blocks of code

The corresponding is: Static variable/class variable; static method; static code

Eg: public class student{

public static int a = 0;

public static int GetValue () {

return A;

}

}

2. Anything that is modified by static is class-level, and all objects are shared together

See Example:

1  Public classUser {2     Private Static intUsernumber = 0 ;3     4      PublicUser () {5Usernumber + +;//add 1 for each object you create6     }7     8      Public Static voidMain (string[] args) {9User user1 =NewUser ();//at this point the Usernumber is 1TenUser user2 =NewUser ();//at this point the Usernumber is 2 One          ASystem.out.println ("User1 usernumber:" +user.usernumber); -System.out.println ("User2 usernumber:" +user.usernumber); -     } the }     ------------- - Output: -User1 Usernumber:2 +User2 Usernumber:2
View Code3. You can access it directly with the class name, without having to instantiate an object for use.

Eg: student.getvalue ();//Direct class name call

or Student s = new Student ();

S.getvalue ();//can also be invoked by the instance of Mr., but the first recommended

4. Use static to be aware of

4.1. Static variables must be initialized when they are defined , and the initialization time is earlier than non-static variables.

4.2. Static modified method, you can only call a static variable or method, and you cannot call a variable or method that is not static.

4.3. cannot refer to this, super in any form. (because they are not static.)

Summary: Whether it is a variable, a method, or a block of code, as long as the static decoration, is when the class is loaded, it is "ready", that is, can be used or has been executed, can be executed from the object.

Conversely, if there is no static, you have to rely on the object instance, Remember two points, usually static only two meaning, the rest / share

Reference : Very detailed here

The Static keyword for 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.