Java Diary (3) class initialization problem (csdn a question)

Source: Internet
Author: User
Problem I added an output "7" to the original question, which is easy to explain the time when the parent class was initialized;

public class Test2 extends Test1 {
{
System.out.print ("1");
}

Test2 () {
System.out.print ("2");
}

static {
System.out.print ("3");
}

{
System.out.print ("4");
}

public static void Main (string[] args) {
New Test2 ();
}
}

Class Test1 {
{
System.out.print ("7");
}

Test1 () {
System.out.print ("5");
}

static {
System.out.print ("6");
}
}

Program execution Results: 6375142
Call Order:
1. Load the class first: Initialize the static variable, initialize the static variable of the parent class, then the static variable of the subclass;
2, initialization of the class: Before the subclass initialization, the initialization of the parent class, and the parent class constructor call;
3, the final initialization of the subclass, call the subclass construction method;

In Chinese Tij, it is not wrong to say that the constructor of the parent class executes before the constructor method of the subclass, but it is not

Perfect, the constructor of the parent class was executed before the subclass was initialized.




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.