为什么这个Java程序中的set 不起作用

首先创建一个Employee类:
import java.util.Date;
import java.util.GregorianCalendar;

class Employee {

private String name;
private double salary;
private Date hireDay;

public Employee() {

}

public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}

public String getName() {
return name;
}

public double getSalary() {
return salary;
}

public Date getHireDay() {
return hireDay;
}

public void setName(String name) {
this.name = name;
}

public void setSalary(double salary) {
this.salary = salary;
}

public void setHireDay(int year, int month, int day) {
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
this.hireDay = calendar.getTime();

}

public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
}

然后创建它的测试类:

public class EmployeeTest {
public static void main(String[] args) {
// fill the staff array with three Employee objects
Employee[] staff = new Employee[4];

staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

staff[3].setName("Tom");
staff[3].setSalary(10000);
staff[3].setHireDay(1984, 7, 31);

for (Employee e : staff)
e.raiseSalary(5);

for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary="
+ e.getSalary() + ",hireDay=" + e.getHireDay());
}
}

运行时候报staff[3].setName("Tom");这行空指针异常,请问这是为什么?如何修改

"staff[3].setName("Tom"); "
上面这行代码中,staff[3]这个对象没有初始化。
Employee[] staff = new Employee[4]; 这只是建立了数组的引用,却没有初始化它们。要使用变量,就得先赋值,就像:
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
上面就是初始化了。
可以这样:
staff[2] = new Employee();
staff[3].setName("Tom");
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-04-19
staff[3]根本没有放入对象的引用,也就是说里面根本没有Employee的实例的引用,staff数组本身并没有setName这样的方法,而是Employee的实例才有,你这样调用当然会出错了