Java static code blocks, literacy stickers

Source: Internet
Author: User

A class can use static blocks of code that are not contained in any method body. When a class is loaded, a static block of code is executed and executed only once. The actions that cause the class to be loaded include: using the static properties or methods of any class, the object of the new class (declaring the object of the class does not cause a static block of code to be executed). Static code blocks are often used for initialization of class properties. Take a look at the following tests:

Class person{Public Person    ()    {        System.out.println (' 1.public person () ');    }    static {        System.out.println ("The 2.Person class is called!");}    } public class teststaticdemo5{    static    {        System.out.println ("3.teststaticdemo5 class is called!");    }        public static void Main (String args[])    {        System.out.println ("4. The program starts executing! ");        New person ();        New person ();    }}

Save the above code as a file Teststaticdemo5.java. "Javac Teststaticdemo5.java" is compiled and executes "Java TestStaticDemo5", printed as follows:

The static code block of the 3.teststaticdemo5 class is called!
4. The program starts to execute!
The static code block of the 2.Person class is called!
1.public person ()
1.public person ()

Java static code blocks, literacy stickers

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.