[Java] inherited execution sequence of Constructors

Source: Internet
Author: User

Problem:

Subclass inherits the parent class. What is the execution sequence of constructors and public attributes?

Sample Code

[Java]
<Span style = "font-family: Times New Roman; font-size: 14px;"> public class A extends C {
B B = new B ();
Static H h = new H ();
Static {
System. out. println ("this is static tack ");
}
 
Static void I (){
System. out. println ("this is static metod ");
}
 
Public (){
System. out. println ("this is class ");
 
}
 
Public static void main (String [] args ){
A a = new ();
}
}
 
Class B {
Public B (){
System. out. println ("this is class B ");
}
}
 
Class C {
D d = new D ();
Static E e = new E ();
Final F e1 = new F ();
Static final G e2 = new G ();
 
Public C (){
System. out. println ("this is class C ");
}
}
 
Class D {
Public D (){
System. out. println ("this is class D ");
}
}
 
Class E {
Public E (){
System. out. println ("this is class E ");
}
}
 
Class F {
Public F (){
System. out. println ("this is class F ");
}
}
 
Class G {
Public G (){
System. out. println ("this is class G ");
}
}
 
Class H {
Public H (){
System. out. println ("this is class H ");
}
} </Span>
Execution result:

This is class E
This is class G
This is class H
This is static tack
This is class D
This is class F
This is class C
This is class B
This is class

Execution sequence:

1. implement common static attributes of the parent class or static block-level code

2. implement its own public static attributes

3. Implement the common attributes of the parent class

4. Execute the construction method of the parent class

5. implement its own public attributes

6. Execute the constructor itself

7. Do not execute static methods

Supplement:

When the parent class has multiple constructors, if the subclass uses super (parameter information) to indicate that a constructor with parameters is called for the parent class, no constructor without parameters is executed.

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.