Java block, static block, constructor, inherited execution sequence

Source: Internet
Author: User

Http://d-y-zh.javaeye.com/blog/607027

 

Non-static statement block, first seen.

 

Public class test
{
Public static void main (string [] AGRs)
{
Son son = new son ();
}
}

Class super
{
Public super ()
{
System. Out. Print ("A/T ");
}
{
System. Out. Print ("B/T ");
}
Static
{
System. Out. Print ("C/T ");
}
}

Class son extends super
{
Public son ()
{
System. Out. Print ("d/t ");
}
{
System. Out. Print ("E/t ");
}
Static
{
System. Out. Print ("F/T ");
}
}

Static objects belong to classes, and non-static objects belong to instances.

The static statement is executed first before it is non-static.

In the above example, we also need to consider the inheritance issue.

First, the parent class static --> C

Then the subclass static --> F

A non-static block can be considered as the first part after the parent class constructor is executed in the constructor. (The first line of the constructor has a default Super () call, which is to call the parent class constructor ).

Execute the parent class constructor at this time:

Non-static block of the parent class --> B

Parent class constructor block -->

Then the sub-class constructor:

Subclass non-static block --> E

Subclass constructor block --> d

Summary:

C f B A E d

It is worth noting that static things are executed only once, that is, when classes are loaded.

If the main function is changed:

Java code

Public static void main (string [] AGRs) {son = new son (); son son2 = new son ();}

The execution result is as follows:

C f B a e d B A e d

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.