对象初始化语块执行顺序:

static initialization block

new Employee1----------

instance field initialization

object initialization block
Employee(String name, double salary)

 

new Employee2----------
instance field initialization
object initialization block
Employee(String name, double salary)
Employee(double salary)

 

new Employee3----------
instance field initialization
object initialization block

 Employee()

 

1676 xkfx 30000.0
1677 Employee #1677 60000.0
1678 0.0

Process finished with exit code 0

 

import java.util.Random;

/**
 * Created by xkfx on 2016/12/14.
 *  only 20
 */
public class Employee{
    private static int nextId;

    private int id;
    private String name = test(); // instance field initialization
    private double salary;

    // static initialization block
    static{
        Random generator = new Random();
        nextId = generator.nextInt(10000);
        System.out.println("static initialization block");
    }

    // object initialization block
    {
        id = nextId ++;
        System.out.println("object initialization block");
    }

    // three overloads constructors
    public Employee(String name, double salary){
        this.name = name;
        this.salary =salary;
        System.out.println("Employee(String name, double salary)");
    }

    public Employee(double salary){
        // calls the Employee(String, double) constructor
        this("Employee #" + nextId, salary);
        System.out.println("Employee(double salary)");
    }

    // the default constructor
    public Employee(){
        // name initialized to "" --see above
        // salary not explicitly set--initialized to 0
        // id initialized in initialization block
        System.out.println("Employee()");
    }

    public String getName(){
        return this.name;
    }

    public double getSalary(){
        return this.salary;
    }

    public int getId(){
        return this.id;
    }

    private String test(){
        System.out.println("----------instance field initialization");
        return "";
    }
}

main加载程序逻辑:

/**
 * Created by xkfx on 2016/12/14.
 */
public class ConstructorTest{
    public static void main(String[] args){
        Employee[] staff = new Employee[3];

        staff[0] = new Employee("xkfx" , 30000);
        staff[1] = new Employee(60000);
        staff[2] = new Employee();

        for(Employee e: staff){
            System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
        }
    }
}

 

网上copy的一段不知道有没有误

 

java程序在内存中的存储分配情况:

堆区: 
1.存储的全部是对象,每个对象都包含一个与之对应的class的信息。(class的目的是得到操作指令) 
2.jvm只有一个堆区(heap)被所有线程共享,堆中不存放基本类型和对象引用,只存放对象本身 
栈区: 
1.每个线程包含一个栈区,栈中只保存基础数据类型的对象和自定义对象的引用(不是对象),对象都存放在堆区中 
2.每个栈中的数据(原始类型和对象引用)都是私有的,其他栈不能访问。 
3.栈分为3个部分:基本类型变量区、执行环境上下文、操作指令区(存放操作指令)。 
方法区: 
1.又叫静态区,跟堆一样,被所有的线程共享。方法区包含所有的class和static变量。 
2.方法区中包含的都是在整个程序中永远唯一的元素,如class,static变量。