Java Instance variable initialization

Source: Internet
Author: User

The--java instance variable initialization time that is thought of by a face question:2015-10-07 16:08:38 read:23 Comments:0 Favorites:0 [Point I collection +]

The topic originates from the push of the public number (programmer's): an object-oriented question for Ctrip's Java engineers

The problem is this: ask for the output of the following program:

Public Class Base{ Private StringBaseName= "Base; Public Base() {Callname(); } Public void Callname() { System.Out.println(BaseName); } Static Class Sub Extends Base { Private StringBaseName= "Sub"; Public void Callname() { System.Out.println(BaseName) ; } } public< Span class= "PLN" > staticvoid  (string[] Args { base b = new sub (); }}          /span>                

Obviously at the beginning I also did wrong, the reason is very simple, this topic examines what I probably know, but before learning the loading mechanism of the class, the initialization process of the class is more understanding, but the initialization process of the instance variable is rather vague. There are also some difficulties involved in the following: inheritance when the subclass of the same name property does not overwrite the parent class, the parent class's properties are hidden, in the parent class constructor called virtual function to cause polymorphism of the abnormal code.

The next step is to take a look at the Java Virtual machine (Bill venners) to get a clear idea of the problem. Below I will try to be simple and clear analysis of its clarity.

In front of me in the Java class loading and initialization simple explanation of the class loading link initialization process, interested can see, there is also a perverted topic.

procedure for initializing an instance variable of a class
Once a class is loaded, the connection is initialized, he can be used at any time, the program can access his static field, call a static method, or create an instance of it. In Java programs, classes can be instantiated explicitly or implicitly, in four ways: explicitly using the new operator, calling the Newinstance () method of a class or constructor object, or invoking the Clone () method of any existing object Or deserialized by the GetObject () method of the ObjectInputStream class.

When a virtual machine creates a new instance, it needs to allocate memory to the instance of the saved object in the heap. All variables declared in the object's class and in its superclass (including hidden instance variables) are allocated memory. Once the virtual machine has prepared heap memory for the new object, it immediately initializes the instance variable to the default initial value. This is similar to when a class variable is given the default initial value in the preparation phase of the link.

Once the virtual machine has finished allocating memory for the new object and initializing the instance variable to the initial value of the default positive acknowledgment, the initial value of the instance variable is followed. This is called the instance initialization method of the object, called the < init > () method in the Java class file, similar to the class initialization < Clinit > () method.

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

  • Call another < init > () method
  • Implementing initialization of any instance variable
  • Code to construct the method body

In fact, the following conditions are generally true:

  • The constructor explicitly calls another constructor in the same class, which is called this (), and its corresponding < init > () method consists of two parts:
    A similar < init > (...) Invocation of the method
    The byte code of the method body that implements the corresponding construction method

  • Not starting with this (), nor object, consists of three parts:
    Super-class < Init > () method call
    Byte code of the initialization method for arbitrary instance variables
    The byte code of the method body that implements the corresponding construction method

What do you mean? The simple idea is that < init > () is the constructor from the byte-code angle of the class file, which is usually made up of several parts of the Java code.

Super class < Init > () method call ——————— > corresponding super ()
Bytecode for arbitrary instance variable initialization methods ———— > corresponding assignment code when defining a variable
The bytecode of the method body that implements the corresponding construction method--the code inside the constructor

Note: Java guarantees that the parent class must also be initialized before an object is initialized. There are mechanisms to ensure that Java enforces that the first sentence in any class's constructor must be to call the parent class constructor or another constructor defined in the class. If there is no constructor, the system adds a default parameterless constructor, and if our constructor does not show a constructor that calls the parent class, the compiler automatically generates an parameterless constructor for the parent class.

Give me a chestnut:

class B { private Span class= "Hljs-keyword" >int b = 10;public  () { b = 100;}}          /span>                

After compiling into a class file, use the command javap-c B.class to Decompile

Obviously you can see that initialization < init > () is divided into three parts

Part I: the <init> () method of the parent class0:Aload_01:Invokespecial#1 MethodJava/lang/object. " <init> ":() VPart Two: instance variable initialization, which is the assignment when defining a variable4:Aload_05:Bipush107:Putfield#2 //Field b:i//Part III: Constructor method body 10: Aload_011: Bipush < Span class= "lit" >10013:  Putfield  #2  //Field b:i16< Span class= "pun" >: return     

Learn here to summarize what you have learned before:
The order in which the Java instance variables are initialized is the constructor code block, which is directly assigned to the initialization code (XXX->XXX->XXX) of the parent class, as defined by the variable.

Look back at the beginning of the question:
Until the base class and sub classes complete the initialization process (class initialization complete)
Before initializing a Sub object, first open memory in the heap area and assign null to the basename in the subclass and to the basename (hidden) in the parent class.
Following the initialization of the object, the initialization code contains three parts because the sub class's constructor is not written:

    1. Super (); Call the base class's init<> ()

      1. Calling super () is the init<> () of the object class.
      2. BaseName = "base"; here is the baseName assignment of the parent class.
      3. inside the parent constructor: Call Callname () because the function is called inside the sub class, so the current this is actually a subclass, because the Callname method of the sub-class sub is called by the polymorphic BaseName variable is not yet assigned or null!
    2. BaseName = "Sub"; Here is the BaseName assignment for the subclass.

    3. Empty (constructors have nothing)

So the output null!

Java Instance variable initialization

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.