code block execution order.

Source: Internet
Author: User

Class father1{

static{
System.out.println ("..... static Father ...");
}

{
System.out.println ("... Parent class non-static ... ");
}

Public Father1 () {
SYSTEM.OUT.PRINTLN ("---the construction method of the parent class----");
}
}

Class Son1 extends father1{

static{
System.out.println ("..... static Son ...");
}



Public Son1 () {
SYSTEM.OUT.PRINTLN ("---sub-class construction method-----");
}
{
System.out.println ("... Sub-class non-static ... ");
}
}

public class Demo3 {


static{
System.out.println (".... Main function static code ... ");
}

{
System.out.println ("... Main function non---------static code ... ");
}

public static void Main (string[] args) {

Son1 s = new Son1 ();
SYSTEM.OUT.PRINTLN ("----output completed-------");
Demo3 d = new Demo3 ();
}

}

Execution Result:

.... Main function static code .....
.... static Father .....
.... static Son .....
..... Parent class non-static ...
---The Parent class construction method----
..... Sub-class non-static ...
---sub-class construction method-----
----output is complete-------
..... Main function non---------static code ...

So the order is:

Executes a static block of code from the same class as the main function.

Executes a static block of code from the parent class.

Executes a static block of code from a subclass.

A non-static block of code is executed before the new object, before constructing the method;

Parent class Construction Method

Sub-class non-static

Sub-class construction methods

code block 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.