In a Java class, a member variable is assigned the first, followed by a static constructor, again a constructor

Source: Internet
Author: User

Title is the conclusion that if someone asks you the Java class member initialization order and initialization block knowledge then answer him. Here's the code:

 Packagecom.test; Public classtestclass{//member variable assignment the first execution of the    Private Static intM1=1; Private intM2=1; //Static constructors A second execution    Static{System.out.println ("Member variable assignment precedes static constructor m1=" +M1); M1=2; }        //The third execution of the constructor function     PublicTestClass () {System.out.println ("Static constructors precede constructor m1=" +M1); M1=3; System.out.println ("Member variable assignment precedes constructor m2=" +m2); M2=3; }         Public voidprintm1m2 () {System.out.println ("M1=" +M1); System.out.println ("M2=" +m2); }         Public Static voidMain (string[] args) {TestClass T=NewTestClass ();    T.PRINTM1M2 (); }}

Console output:

The member variable is assigned before the static constructor m1=1 the static constructor is assigned a value before the constructor M1=2 member variable before the constructor m2=1M1 =3m2 =3

In a Java class, a member variable is assigned the first, followed by a static constructor, again a constructor

Related Article

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.