请帮我看看为什么变量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;
}
}
------解决方案--------------------只对类进行了初始化,没有调用setXXX()修改私有成员变量。
private static int nextId = 1;//为什么此处不在下面的构造器中赋值,像id一样?
这个变量是一个静态变量,在类初始化之前就被初始化,所以要有初始值。
------解决方案--------------------setId()
------解决方案--------------------你都没用自增操作符 怎么自增啊