对象构造
- 静态初始化块
- 实例域初始化
- 对象初始化块
- 重载构造器
- 用
this(...)
调用另一个构造器 - 无参数构造器
在类第一次加载的时候,将会进行静态域的初始化。所有的静态初始化语句以及静态初始化块都将依照类定义的顺序执行。在调用构造器实例化一个对象时,具体的处理步骤是:
1). 所有的数据域被初始化为默认值(0、false、null)。
2). 按照在类声明中出现的次序,依次执行所有的初始化语句和初始化块。
3). 如果构造器第一行调用了第二个构造器,则执行第二个构造器的主体。
4). 执行这个构造器的主体。
import java.time.LocalDate;
import java.util.Random;
public class Employee {
//fields
private static int nextId = 1;
private int id;
private String name = ""; // instance field initialization
private double salary;
private LocalDate hireDay;
// static initialization block
static {
Random generator = new Random();
// set nextId to a random number between 0 and 9999
nextId = generator.nextInt(10000);
}
// object initialization block
{
id = nextId;
nextId++;
}
//overloaded constructors
public Employee(String name, double salary, int year, int month, int day) {
// calls the Employee(String, double) constructor
this(name, salary);
this.hireDay = LocalDate.of(year, month, day);
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
// the default constructor
public Employee() {
//name initialized to "" --see above
//salary not explicitly set --initialized to 0
//id initialized in initialization block
//hireDay not explicitly set --initialized to null
}
//methods
public String getName() {
return this.name;
}
public double getSalary() {
return this.salary;
}
public LocalDate getHireDay() {
return this.hireDay;
}
public void raiseSalary(double byPercent) {
double raise = this.salary * byPercent / 100;
this.salary += raise;
}
public void setId() {
this.id = nextId;
nextId++;
}
public static int getNextId() {
return nextId;
}
}