静态初始化块只在类加载时执行,且只会执行一次,同时静态初始化块只能给静态变量赋值,不能初始化普通的成员变量。
import java.util.Random;
public class ConstructorTest
{
public static void main(String[] args)
{
//fill the staff array with three Employee objects
Employee01[] staff = new Employee01[3];
staff[0] = new Employee01("周杰伦", 40000);
staff[1] = new Employee01(60000);
staff[2] = new Employee01();
for(Employee01 e : staff)
{
System.out.println("名字:" + e.getName() + ", id = " + e.getId() + ", 薪水:" + e.getSalary());
}
}
}
class Employee01{
private static int nextId;
private int id;
private String name = ""; //instance field initialization
private double salary;
// 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++;
salary = 100;
}
// three overload constructor 三个重载构造器
public Employee01(String name, double salary)
{
this.name = name;
this.salary = salary;
}
public Employee01(double salary)
{
this("Employee" + nextId, salary);
}
public Employee01()
{
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
}
名字:周杰伦, id = 6020, 薪水:40000.0
名字:Employee6021, id = 6021, 薪水:60000.0
名字:, id = 6022, 薪水:100.0