Java Free blocks (static and non-Static) (reprinted)

Source: Internet
Author: User

Free blocks in Java are divided into two types:

Static blocks and non-static blocks

Static blocks:

 Public class Test {2     Static int x = ten; 3     // static block: The execution time of a static block is when the class file is loaded , and the static block executes 4     / more static blocks at a time, in the order of occurrence 5     static{6         x+=5; 7     }8 }

Non-static blocks:

 Public class Test {2     // non-static blocks: Each time an object is initialized, a non-static block is executed, and a 3//inheritance relationship is performed before the constructor executes: the constructor of the parent class, the      non-static block of the parent class, and its own free block, Own constructor 4     {5         System.out.println ("before"); 6     }7}

Test Demo:

  Public classTest {2 3Static intx = 10; 4//static blocks: The execution time of a static block is when the class file is loaded, and the static block executes only once5//multiple static blocks, executed in order of occurrence6Static{ 7 x+=5; 8     } 9 Public Static voidMain (string[] args) {10NewTest ();11System.out.println (x);12     }13//static Block14Static {X/=3;16     }17 PublicTest () {System.out.println ("constructor");19     }20//non-static blocks: Each initialization of an object results in the execution of a non-static block, which executes before the constructor executes21st//Inheritance Relationship: The constructor of the parent class, the non-static block of the parent class, and its own constructor, the free block,22     {System.out.println ("Before");24     }25}

Console output:

before constructor 5

Java Free blocks (static and non-Static) (reprinted)

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.