Initialization of Java instance variables

Source: Internet
Author: User

Initialization of Java instance variables

This question comes from the public account (what programmers do) Push: An Object-Oriented interview question by Ctrip Java engineers

The question is as follows: Find the output of the following program:

public class Base{   private String baseName = "base";   public Base()   {       callName();   }   public void callName()   {       System. out. println(baseName);   }   static class Sub extends Base   {       private String baseName = "sub";       public void callName()       {           System. out. println (baseName) ;       }   }   public static void main(String[] args)   {       Base b = new Sub();   }}

Obviously, I also did something wrong at the beginning. The reason is very simple. I probably know what this question is about, but I still know the class initialization process when I learned the class loading mechanism, however, the initialization process of instance variables is vague. It also involves the following difficulties: When inheriting, attributes of the same name of the subclass will not overwrite the parent class, and the attributes of the parent class will be hidden; calling a virtual function in the constructor of the parent class causes the abnormal code of polymorphism.

Next, let's take a look at the Java Virtual Machine (Bill Venners) to have a clear understanding of this issue. Below I will try to make it simple and clear.

Previously, I briefly explained the initialization process of the class loading link in JAVA class loading and initialization. If you are interested, you can see that there is also an abnormal question in it.

Class instance variable initialization process
Once a class is loaded and initialized, it can be used at any time. The program can access its static fields, call static methods, or create its instances. Classes can be explicitly or implicitly instantiated in Java programs. There are four ways: explicitly using the new operator; calling the newInstance () method of the Class or Constructor object; call the clone () method of any existing object, or use the getObject () method of the objectInputStream class for deserialization.

When a VM creates a new instance, it must allocate memory in the heap for the instance storing objects. All variables declared in the object class and its superclass (including hidden instance variables) need to be allocated memory. Once the VM prepares heap memory for a new object, it immediately initializes the instance variable to the default initial value. This is similar to assigning the default initial value to a class variable in the preparation phase of the link.

Once the VM allocates memory for the new object and initializes the instance variable to the initial value of positive confirmation, the initial value of the instance variable will be followed. That is, the instance Initialization Method of the called object, which is called the <init> () method in the java class file, similar to the <clinit> () method of class initialization.

A <init> () method may contain three types of code:

Call another <init> () method to initialize the construction method body of any instance variable.

In fact, there are generally the following situations:

The constructor explicitly calls another constructor in the same class, that is, this () is called. Its <init> () method consists of two parts:
A similar <init> (...) Call Method
Implements the bytecode of the method body corresponding to the constructor.

It does not start with this (), nor is it an Object. It consists of three parts:
<Init> () method call of the superclass
Bytecode of any instance variable Initialization Method
Implements the bytecode of the method body corresponding to the constructor.

What does it mean? A simple understanding is that <init> () is a constructor from the byte code perspective of the class file, which is generally composed of several parts in the Java code.

Superclass <init> () method call -------> corresponds to super ()
Bytecode of the initialization method of any instance variable ----> value assignment code corresponding to the definition variable
Implements the bytecode of the method body corresponding to the constructor --> the code in the constructor

Note: Java ensures that the parent class of an object must be initialized before it is initialized. There is a mechanism to ensure that Java requires that the first sentence of any class constructor must be to call the parent class constructor or other constructor defined in the class. If no constructor exists, the system adds the default non-argument constructor. If the constructor of the parent class is not displayed in our constructor, then the compiler automatically generates a non-argument constructor for the parent class.

Example:

class B {  private int b = 10;  public B(){    b = 100;  }}

After being compiled into a class file, use the javap-c B. class command to decompile the file.

Obviously, we can see that the initialization <init> () is divided into three fen? Http://www.bkjia.com/kf/yidong/wp/ "target =" _ blank "class =" keylink "> WPC9wPg0KPHByZSBjbGFzcz0 =" brush: java; ">// The first part: () Method 0: aload_01: invokespecial #1 // Method java/lang/Object ." ":() V // The second part: instance variable initialization, that is, the value assigned to the variable when the definition is 4: aload_05: bipush 107: putfield #2 // Field B: I // Part 3: constructor method body 10: aload_011: bipush 10013: putfield #2 // Field B: I16: return

Here, we will summarize the following content:
The initialization sequence of Java instance variables is the initialization code of the parent class (xxx-> xxx)-> assign values directly when defining variables-> construct function code blocks.

Let's look back at the problem:
The initialization process is completed until the Base class and Sub class are complete)
Before initializing a Sub object, first open the memory in the heap area and assign the baseName In the subclass and the baseName (hidden) in the parent class to null.
Next, execute the initialization process of the object. Since the Sub class constructor is not written, the initialization Code contains three parts:

Super (); call the Base class init <> ()

Call super (), that is, the init <> () baseName = "base" of the Object class. Here, the baseName value of the parent class is assigned. In the parent constructor: Call callName () because this function is called in the Sub class, the current this is actually a subclass, the callName method of the Sub-class is called by polymorphism. At this time, the baseName variable of the Sub-class has not been assigned a value or is null!

BaseName = "sub"; here is the baseName value of the subclass.

NULL (no constructor is available)

So the output is null!

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.