请帮我看看为什么变量id没有自增?
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("abc", 5000);
staff[1] = new Employee("efg", 6000);
staff[2] = new Employee("opq", 7000);
for(int i=0; i<staff.length; i++)
{
System.out.println("name = " + staff[i].getName() + ", salary = " + staff[i].getSalary() + ", and his id is " + staff[i].getId());
}
}
}
class Employee
{
private String name;
private double salary;
private int id;
private static int nextId = 1;//为什么此处不在下面的构造器中赋值,像id一样?
public Employee(String n, double s)
{
name = n;
salary = s;
id = 0;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void setId()
{
id = nextId;
nextId++;
}
public int getId()
{
return id;
}
}
我觉得id应该是1, 2, 3,但是结果是
另外,nextId为什么不在构造器中赋值? ?
[解决办法]
setId() 方法没有调用!
[解决办法]
import java.util.*;
public class Test111 {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("abc", 5000);
staff[1] = new Employee("efg", 6000);
staff[2] = new Employee("opq", 7000);
for (int i = 0; i < staff.length; i++) {
System.out.println("name = " + staff[i].getName() + ", salary = "
+ staff[i].getSalary() + ", and his id is "
+ staff[i].getId());
}
}
}
class Employee {
private String name;
private double salary;
private int id;
private static int nextId = 1;// 为什么此处不在下面的构造器中赋值,像id一样?
public Employee(String n, double s) {
name = n;
salary = s;
id = nextId++; //因为构造函数赋值为0
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void setId() {
id = nextId;
nextId++;
}
public int getId() {
return id;
}
}