Java class Execution order issues

Source: Internet
Author: User

Frequently encountered face questions, one class inherits another class and then asks what the result of the output is. Personal feel is the test class output problem (pro-Test)

First: A single class execution order

Package Test;

public class Person {

static{
System.out.println ("Static block of the parent class");
}

Person () {
System.out.println ("Construction method of the parent class");
}

{
SYSTEM.OUT.PRINTLN ("Non-static code block of the parent class");
}



public static void Main (string[] args) {
System.out.println ("main function of the parent class main");
Person p = new person ();
}

}

Print:

Static block of parent class
Main function of parent class main
Non-static block of code for the parent class
How to construct a parent class

The output is: static block of parent class----the parent class's main function main--> the non-static block of the parent class--the constructor of the parent class

Second: Subclass inherits parent class, creates subclass object, order of code Execution (pro-Test)

Package Test;

public class Sontest extends person {
static{
System.out.println ("Static code block for subclasses");
}
{
SYSTEM.OUT.PRINTLN ("Non-static block of code for subclasses");
}
Sontest () {
System.out.println ("constructor of the subclass");
}
public static void Main (string[] args) {
System.out.println ("Main function of the subclass main");
Sontest s = new Sontest ();
}
}

Print:

Static block of parent class
Static code blocks for subclasses
The main function of the subclass main
Non-static block of code for the parent class
How to construct a parent class
Non-static blocks of code for subclasses
Constructors for subclasses

The output is the static code block of the parent class----The static code block of the subclass--the main function of the subclass--main--> The parent class non-static code block--the constructor of the parent class--The non-static code block of the subclass--the constructor of the child class

Java class Execution order issues

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.