The process of initializing the instance variables of a Java class static blocks, non-static blocks, and the load order of constructors

Source: Internet
Author: User

First look at a Java interview question:

1 public class Baset {2     private String baseName = "base"; 3     //Construction Method 4 public     Baset () {5         callname (); 6
   } 7     //Member Method 8 public     void Callname () {9         //TODO auto-generated method Stub10         System.out.println ("ba SENAME: "+ baseName");     }12   //Static inner class, type "static Class"     Sub extends Baset {//static must be written at the beginning         //static field 15< C17/>private String baseName = "Sub", and the public         sub () {             callname ();         }19         //overriding method         of parent class public void Callname () {             System.out.println ("subname:" + baseName),         }23}24 public     Static void Main (string[] args) {         Baset base = new Sub ();     }28}

The output of this program.

The key to solving this problem is to understand and master the loading process of the class and the invocation of the overriding method after the subclass inherits the parent class:

One, from the order of execution of the program to answer:

1. Compile; when the class is notified, two. class files are generated in the appropriate directory. One is Base.class, the other is Base$sub.class. This time the ClassLoader loads these two. class files into memory

2. Base base= New Sub ():

Declares the parent class variable base reference to the subclass, and the Java ClassLoader loads the Base,sub class into the JVM (Java Virtual machine);

3. The JVM opens up memory space for members of the Base,sub

At this point, the values in the Base and sub classes are null;

4, new Sub ();

The implicit construction method of the sub class is called at this time,

the sub's construction method is essentially:

Public Sub () {

Super ();// Call the construction method of the parent class . Must be in the first row of the constructor method, for what? This is because in the upgrade of some programs, to be compatible with the old version of some features, the parent class is the original initialization information to ensure that//is executed to, and then perform the current

BaseName = "Sub";//Subclass Field Class

}

The new Sub () executes to super () This line of code is run to the parent class to execute, we jump to the parent class in the non-parametric construction method, and finally execute the sub () in the basename = "Sub"

5, public Base ();

the nature of the non-parametric construction method of the parent class is:

Public Base () {

Basename= "base";//Parent field class.

Callname ();

}

The basename assignment of the parent class is "base", and the value is called Callname () after assignment;

6. The Callname () method is overridden in a subclass so that the Callname () of the subclass is called, the Callname method of the subclass is executed, and the output is the value of the basename field of the subclass, and this time the assignment of the field in the constructor of the subclass has not been performed.

7, the constructor of the parent class is finished, this time back to the sub-class, from the next line of super () to continue execution, this time only for the sub-class field basename allocated storage space, and then assigned the value:

It can be seen that callname () of the subclass has been executed before basename = "Sub" is executed, so the basename of the subclass is the default value state null;

Ii. write two additional procedures for more specific analysis

1, the first program:

 1 public class Initialordertest {2//Variable 3 public String field = "Variable"; 4//static variable 5 public static string St aticfield= "Static variable"; 6//Parent class static method 7 public static void Order () {8 System.out.print ("Parent static Method"); 9 System.out.println ("Stati Cfield: "+staticfield"); 10}11 12//Static initial code block of static{14 System.out.println ("Static initialization Block"), System.           Out.println ("Staticfield:" +staticfield); 16}17//initialization code block ("Initialization code block"), 20 System.out.println ("field:" +field); 21}22//constructor All public initialordertest () {SYSTEM.OUT.P Rintln ("constructor");}27 public static void Main (string[] args) {System.out.println ("-----[[---- ---"): System.out.println (Initialordertest.staticfield); Initialordertest.order (); SYSTEM.OUT.P RINTLN ("------]")------"), initialordertest i = new Initialordertest (), System.out.println ("-----[[------ -"); 35        System.out.println (Initialordertest.staticfield); Initialordertest.order (); PNs System.out.println (" ------]]------"); 38 39}40}

The result of the execution is:

Summary of the first program :

1), the blocks in Java are divided into static blocks (static{}) and non-static blocks ({}), and the execution of these two types is different:

The execution time of a non-static block is: Before the constructor is executed. The execution time of a static block is: executed when the class file is loaded.

Properties of the static type are also executed when the class is loaded.

2), the process of initializing instance variables of the Java class is visible:

static blocks (static{}) are executed sequentially, then non-static member variables are initialized, non-static code blocks ({}) are executed, and the constructor method is finally executed.

The static type is executed in sequence with the static block.

--------------------------------------------------------------------------------------------------------------- ------------------------------------

2, the second program:

 1 public class Basetest {2///parent class variable 3 private String baseName = "base"; 4//parent class static variable 5 private static Stri Ng Staticfield = "Parent class static variable"; 6//Parent class static method 7 public static void Order () {8 System.out.println ("Parent static Method-"); 9 System.out.println ("         Staticfield: "+ Staticfield); 10}11//Parent class static initial code block (" Static initialization code block of parent Class-") 14 System.out.println ("Staticfield:" + Staticfield); 15}16//initialization code block, {System.out.println ("Parent Non-static         Initialize code block-""), System.out.println ("BaseName:" + baseName); 20}21//constructor of public basetest () {23 System.out.println ("Parent class construction Method"); Callname (); 25}26//member method the public void Callname () {System . OUT.PRINTLN ("Parent class Callname Method-"); System.out.println ("BaseName:" + baseName); 30}31 32//Static internal class Stati     C Class Sub extends Basetest {34//Subclass variable-Private String baseName = "Sub"; 36//Subclass static Variable 37    private static String Staticfield = "Subclass static variable"; 38 39//Subclass static method n public static void Order () {41         System.out.println ("Subclass static Method-"), System.out.println ("Staticfield:" + Staticfield); 43}44 45 Subclass static initialization code block SYSTEM.OUT.PRINTLN ("Subclass static initialization code block-"), System.out.println ("Stat Icfield: "+ Staticfield); 49}50//subclass non-static initialization code block {System.out.println (" subclass non-static initialization code block-" ), System.out.println ("BaseName:" + baseName), and}55, the public Sub () {System. Out.println ("Sub-Class construction method"); Callname ();}60-System.ou public void callname () T.println ("Subclass Overrides Parent class Callname Method-"); System.out.println ("BaseName:" + baseName);}65}66 Lic static void Main (string[] args) {basetest b = new Sub (); System.out.println ("-----[ [-------];B.order (); System.out.println (Sub.staticfield); System.out.println (Basetest.staticfield); Setest.order (); System.out.println ("------]]------"); 77 78}79}

Execution Result:

Summary of the second procedure :

1), the order in which Java initialization is visible:

1  1 Parent class static variable initialization 2  2 parent class static code block-static{} 3  3 subclass static Variable initialization 4  4 subclass static code block-static{} 5  5 parent class non-static variable initialization 6  6 parent class non- Static code block-{} 7  7 Parent class construction method 8  8 Subclass non-static variable initialization 9  9 subclass non-static code block-{}10 10 Subclass construction Method

The process of initializing the instance variables of a Java class static blocks, non-static blocks, and the load order of constructors

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.