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