Java object Initialization Order validation sample _java

Source: Internet
Author: User

Copy Code code as follows:

Public class derive extends Base
{
Private member M1 = new Member (' member 1 ');
{
System.out.println ("Initial block ()");
}

Public derive () {
System.out.println ("Derive ()");
}

Private member M2 = new Member (' Member 2 ');
private int i = GetInt ();

private int getInt ()
{
System.out.println ("GetInt ()");
return 2;
}

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

Class Base
{
Public Base ()
{
System.out.println ("Base ()");
}
}

Class Member
{
Public member (String m)
{
System.out.println ("Member ()" +m);
}
}
/* Program output:
Base ()
Member () 1
Initial block ()
Member () 2
GetInt ()
Derive ()
*/



The conclusion is as follows: Without considering the initialization of static members, when a constructor of an object is invoked, the program first invokes the constructor of the parent class (you can specify the constructor of the parent class by using the Super keyword, otherwise the parameterless constructor is called by default, and it needs to be called in the first line of the constructor of the subclass). The initialization function and static initialization block of the static member variable are then executed in the order of the Code, and the member variable is given a default value if no value is specified, that is, the base data type is 0 or FALSE, the object is null, and the own constructor is last called.

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.