Static keywords in java and javastatic keywords

Source: Internet
Author: User

Static keywords in java and javastatic keywords

Study Notes, materials from:

Http://www.cnblogs.com/dolphin0520/p/3799052.html

Static keywords can be added to methods, member variables, and code blocks. Class.

1. static Method

The static method can be accessed directly without class instantiation. In static methods, non-static member variables and non-static member methods cannot be called because non-static member methods/variables must depend on specific objects.

2. static variables

Static variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects and have only one copy in the memory, it is initialized only when the class is first loaded. Non-static variables are owned by objects. They are initialized when an object is created and have multiple copies. The copies of each object do not affect each other.

Static member variables are initialized in the defined order.

3. static code block

It can be used to initialize some member information.

Public class testClassA {public static int val = 1; static {System. err. println ("11:" + val); val = 2; System. err. println ("22:" + val);} public static int getVal () {return val ;}} System. err. println (testClassA. getVal ());

Result:

 

Notes:

1. static member variables can be accessed by class objects after instantiation, and static methods can also be accessed by objects, but there is a warning.

2. Local variables cannot be static.

3. The static code block takes precedence over the constructor.

 

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.