Java:调用构造器的具体处理步骤

《Java 核心技术 卷1》关于调用构造器的具体处理步骤的叙述是:

调用构造器的具体处理步骤

  1. 所有数据域被初始化为默认值(0、false或者null)。
  2. 按照在类说明中出现的次数,一次执行所有域初始化语句和初始化块。
  3. 如果构造器第一行调用了第二个构造器,则执行第二个构造器主体。(this(“Employee #” + nextId, s)只能放在第一行,否则编译出错。
  4. 执行这个构造器的主体。
    怎么理解呢?接来下我们代码分析
public class ConstructorTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("Harry", 4000);
        staff[1] = new Employee(6000);
        staff[2] = new Employee();      
        for(Employee e:staff)
        {
            System.out.println("name="+e.getName()+" id="+e.getId()+" salary="+e.getSalary());
        }
    }
}

Employee类源代码

package com.ustc.constructor;
import java.util.Random;
public class Employee {
    private static int nextId;
    private int id;
    private String name = "";
    private Double salary=assignId();
    //static initialization block
    static {
        Random generator = new Random();
        nextId = generator.nextInt(10000);
    }   
    //object initialization block
    {
        id = nextId;
        nextId++;
    }
    public Employee(String n, double s) {
        name = n;
        salary = s;
    }
    public Employee(double s) {
        this("Employee #" + nextId, s);
    }
    public Employee() {
        salary=10000d;
        System.out.println("name="+name+" id="+id+" salary="+salary);
    }
    public String getName() {
        return name;
    }
    public double getSalary() {
        return salary;
    }
    public int getId() {
        return id;
    }
}

staff[0]对象初始化

1.先执行静态域

static {
        Random generator = new Random();
        nextId = generator.nextInt(10000);
    }   

2.构造器参数拷贝,不执行构造器主体

Employee(String n, double s)//这时 n=Harry s=4000

3.实例域初始化

private String name = "";

4.初始化块

{
        id = nextId;
        nextId++;
}

5.执行构造器的主体

name = n;
salary = s;

staff[1]对象初始化

1.执行一个参数的构造器

public Employee(double s) {
        this("Employee #" + nextId, s);
}

2.执行被调用的构造函数的参数拷贝,但是不执行构造器主体

Employee(String n, double s)//这时 n=Employee #3865 s=6000

3.实例域初始化

private String name = "";

4.初始化块

{
        id = nextId;
        nextId++;
}

5.执行被调用构造器的主体

name = n;
salary = s;

6.如果构造器有主体,则执行构造器主体

staff[2]对象初始化

1.执行无参构造器,构造器主体还没执行

public Employee() 

2.实例域初始化

private String name = "";

3.初始化块

{
        id = nextId;
        nextId++;
}

4.执行构造器的主体

salary=10000d;
System.out.println("name="+name+" id="+id+" salary="+salary);

你可能感兴趣的:(Java)