本程序展示类类的一部分特性:
1 重载类构造器
2 用this(....)调用另一个构造器
3 无参构造器
4 在声明中初始化
5 在构造器中初始化
6 初始化块
7 静态初始化块
//主函数如下:
public class ConstructorTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee();
staff[1] = new Employee(6000);
staff[2] = new Employee("魏金浩",7000);
for (Employee employee : staff) {
System.out.println("name = " + employee.getName() + ",id = " + employee.getId() + ",salary = " + employee.getSalary());
}
}
}
import java.util.Random;
public class Employee {
private static int nextId;
private int id;
private String name = ""; //在声明中初始化
private double salary;
//静态初始化块
static {
Random r = new Random();
nextId = r.nextInt(1000);
}
//初始化块
{
id = nextId;
nextId++;
}
//构造函数
public Employee() {
}
public Employee(String name,double salary) {
this.name = name;
this.salary = salary;
}
public Employee(double salary) {
this("Employee # " + nextId,salary); //在构造函数中调用构造函数
}
//类访问器
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
1 按照在类中出现的次序,在类第一次加载时执行静态代码块初始化和静态声明中初始化
2 所有的数据域被初始化为默认值
3 按照在类中出现的次序,执行代码块初始化和声明中初始化
4 如果构造函数中调用了构造函数,则先执行第二层构造函数在执行第一层构造函数
该段代码打印结果如下:
name = ,id = 830,salary = 0.0
name = Employee # 831,id = 831,salary = 6000.0
name = 魏金浩,id = 832,salary = 7000.0