Initialization Order of Java objects

Source: Internet
Author: User

Recently I found an interesting question, the answer to this question at first glance deceived my eyes. Take a look at these three classes:

Package com.ds.test;

public class Upper {
String upperstring;

Public Upper () {
Initializer.initialize (this);
}
}

Package com.ds.test;

public class Lower extends Upper {

String lowerstring = null;

Public Lower () {
Super ();
System.out.println ("Upper:" + upperstring);
System.out.println ("Lower:" + lowerstring);
}

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

Package com.ds.test;
public class Initializer {
static void Initialize (final Upper anupper) {
if (anupper instanceof Lower) {
Lower Lower = (Lower) anupper;
lower.lowerstring = "lowerinited";
}
anupper.upperstring = "upperinited";
}
}

What output can I get from running the Lower class? In this minimalist example it's easier to see the whole situation, but this happens in reality and there's a lot of code that distracts a person's attention.

Anyway, the output is like this:

upper:upperinited
Lower:null;

Although the String type is used in the small example, the actual code for the Initializer class has a delegate object for registration, which is the same as the function of the Lower class-at least the Lower class is the intent. However, there are some reasons for not working when you run the application. Instead, the default path is used, and the delegate object is not set (null).

Now change the Lower code a little bit:

Package com.ds.test;

public class Lower extends Upper {

String lowerstring;

Public Lower () {
Super ();
System.out.println ("Upper:" + upperstring);
System.out.println ("Lower:" + lowerstring);
}

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

Now the output is this:

upper:upperinited
lower:lowerinited

Did you find the difference in the code?

Yes, this lowerstring field is no longer explicitly set to empty. Why this will be different. Anyway, is the default value of the Reference type field (for example, String here) not empty? Of course it's empty. It turns out that although this tiny change obviously doesn't change the code behavior in any way, it makes the results different.

So, what the hell is going on? When you look at the initialization order, everything becomes clear:

The 1.main () function called the Lower constructor.

An instance of 2.Lower is ready. means that all fields are created and populated with default values, for example, the default value of the reference type is NULL, and the default value for the Boolean type is false. At this point, any inline assignments to the field did not occur.

3. The parent class constructor is called. This is enforced by the nature of the language. So before anything else happens, the Upper constructor is called.

4.Upper This constructor runs and specifies a reference that points to the newly created instance of the Initializer.initialize () method.

The 5.Initializer class attaches a new string to two fields (Upperstring and lowerstring). By using a somewhat dirty instanceof instance check to assign values to those two fields – this is not a particularly good design pattern, but it is also feasible, not to mention so much. Once this occurs, the references to both upperstring and lowerstring are no longer empty.

The 6.initializer.initialize () call is complete, and the Upper constructor is completed as well.

7. Now it becomes interesting: the construction of the Lower instance continues. Assuming that the assignment is not explicitly =null in the declaration of the Lowerstring field, the Lower constructor resumes execution and prints out two strings connected to the field.

However, if there is an explicitly assigned null operation, the execution process is slightly different: when the parent class constructor finishes, any variable initialization is performed before the remaining constructors are run (see Java Language Specification Section 12.5). In this case, the string reference previously assigned to Lowerstring is once again given null. Then proceed with the rest of the function constructs, and now print the value of lowerstring: null.

This is a good example of how we can not only pay attention to some of the details of creating objects (or know where to look at Java coding specifications, print or online), but also show why it is bad to initialize like this. We should not care about Upper subclasses at all. Conversely, if for some reason the initialization of some fields cannot be done in the subclass itself, it will only need some of its own variants of the initialization helper class. In this case, if you use string lowstring or string lowerstring = null is really no different, it should be what it would be.

Initialization Order of Java objects

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.