Java Execution Order

Source: Internet
Author: User

The Java execution sequence is as follows:

1. First load the class that is transferred to all classes.

2. Load the parent class first, and then load the child class.

3. During the loading process, static code blocks are executed.

4.new Constructor () will execute the code block {} before executing constuctor ();

5. Static variables are assigned during the loading process, and static code blocks are executed from top to bottom.

So the output is:

1. Parent class static code block.

2. Subclass static code block.

3. The parent class code block.

4. Parent class constructor.

5. Subclass code block.

6. Sub-class constructors.

1  Packagetest_static;2 3  Public classFathor {4      PublicString name= "Fathor";5      Public StaticString sex= "Man";6     7     {8System.out.println ("This is Fathor ' s code block! ");9     }Ten      One     Static{ Asex= "Male"; -System.out.println ("This is Fathor ' s static code block! "); -     } the      -      PublicFathor () { -System.out.println ("Fathor ' sex is:" +sex); -System.out.println ("This is Fathor ' s Constructor"); +     } -}
1  Packagetest_static;2 3  Public classSonextendsfathor{4      PublicString name = "Son";5     6      Public StaticString sex= "Man";7     8     {9System.out.println ("This is son ' s code block! ");Ten     } One      A     Static{ -sex= "Male"; -System.out.println ("This is son ' s static code block! "); the     } -      -      PublicSon () { -System.out.println ("This is son ' s Constructor"); +System.out.println ("Son sex is" +sex); -     } +}
1  Package test_static; 2 3  Public class Test {4      Public Static void Main (string[] args) {5         New Son (); 6     }7 }

Execution Result:

1  This is Fathor ' s static code block! 2  This is son's static code block! 3  This is Fathor ' s code block! 4 fathor ' sex is:male5 This is Fathor's Constructor6 This is son ' s code block! 7  This is son's Constructor8 son sex is male

Java Execution Order

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.