import java.util.Random;
public class Dome2 {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Ha", 4000);
staff[1] = new Employee(8000);
staff[2] = new Employee();
for (Employee e : staff) {
System.out.println("name=" + e.getName() + " id=" + e.getId() + " salary=" + e.getSalary());
}
}
}
class Employee{
private static int nextId;
private int id;
private String name = "";
private double salary;
static {
Random generator = new Random();
nextId = generator.nextInt(10000);
}
{
id=nextId;
nextId++;
}
public Employee(String name, double salary) {
this.name=name;
this.salary = salary;
}
public Employee(double salary) {
this("Employee #" + nextId, salary);
}
public Employee(){
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
运行结果
name=Ha id=622 salary=4000.0
name=Employee #623 id=623 salary=8000.0
name= id=624 salary=0.0
案例中使用的特性
- 重载构造器
- 用 this(...) 调用另一个构造器
- 无参数构造器
- 对象初始化块
- 静态初始化块
- 实例域初始化
网友评论