Java code execution sequence-Example

Source: Internet
Author: User

Class insect ...{
Private int I = 9;
Int J;
Insect ()...{
System. Out. println ("I =" + I + ", j =" + J );
J = 37;
}
Private Static int X1 = Print ("static insect. x1.initialized ");
Public static int print (string s )...{
System. Out. println (s );
Return 47;
}
}

Class bettle extends insect ...{
Private int K = Print ("bettle. K initialized ");
Public bettle ()...{
System. Out. println ("k =" + k );
System. Out. println ("J =" + J );
}
Private Static int X2 = Print ("static insect. X2 initialized ");
Public static void main (string [] ARGs )...{
System. Out. println ("bettle constructor ");
Bettle B = new bettle ();
}
}

Running result:
Static insect. x1.initialized
Static insect. X2 initialized
Bettle Constructor
I = 9, j = 0
Bettle. K initialized
K = 47
J = 37

Explanation:

To run bettle, you must first load the parent class insect. When loading insect, you must first run all static code. The print () function is created, but not run.
This statement runs: Private Static int X1 = Print ("static insect. x1.initialized ");
After the parent class is loaded, load the subclass bettle and initialize all static code first. Then run: Private Static int X2 = Print ("static insect. X2 initialized ");
Then go to main () and run system. Out. println ("bettle constructor ");
Run bettle B = new bettle (); Create a parent class when creating an object, and set all variables to the initial values (I = 9, j = 0 ), then the parent class constructor is triggered.
After loading the parent class and then loading the subclass, set the first defined value as above: Private int K = Print ("bettle. K initialized"); then run 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.