After a period of time may have to find an internship, today in the dorm opened before the big bricks often placed on the pillow, "Java programming thought" intends to revisit the previous learning points, to see some knowledge about Java initialization, to synthesize the pages and books previously read, write down their understanding of the Java instance variable initialization, For the needs of friends only reference, but also for themselves to accumulate some Java programming should pay attention to the points of knowledge.
Initialization of instance variables in Java can occur in three places: the initial value is specified when the instance variable is defined, the initial value specified in the initialization block for the instance variable, and the initial value specified for the instance variable in the constructor. If you understand the internal initialization of the law, generally in the programming and interview the variable assignment problem can basically be solved.
Initialization principle: in the above three cases, the initialization of the program always first after the memory allocation of the instance variables, and then the three cases in the assignment of the part of the implementation of the constructor, its assignment is always: the constructor of the assignment in the last, the other two in accordance with the program source code order.
Understanding is more abstract, the following gives the code and diagram, and the use of the JAVAP tool provided by the JDK to see the code compilation
Inittest class
public class Inittest {/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubtest A = new test ("Test", 2); System.out.println (a);}} Class Test{string Name;int Age, Public Test (String Name,int age) {this.name = name, This.age = age; weight = 5.0;} {SYSTEM.OUT.PRINTLN ("Execute non-static block"); weight = 3.0;} Double weight = 2.3; Public String toString () {return ' Test[name = ' +name+ ', age = ' +age+ ', weight = ' +weight+ '] ";}}
After executing the main function, the test object is initialized, the Test.class is compiled and viewed.
Declare the instance variable first and assign the corresponding variable memory to the object
Then move all assigned parts to the constructor, in the order shown
In a word, understanding the initialization rules of reference objects is helpful for learning JVM memory operations.
Pick up the flowers--see the initialization inside of the Java instance variable