public class StaticTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
//创建数组 staff 数组长度为3
staff[0] = new Employee("Tom",40000);
staff[1] = new Employee("Dick", 60000);
staff[2] = new Employee("Harry", 65000);
//使用for each 输出数组内的元素
for(Employee e : staff){
e.setId();
System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary=" + e.getSalary());
}
//采用public void setId() 来得到每一个员工的Id
int n = Employee.getNextId();
System.out.println("Next available id=" + n);
}
}
class Employee{
//设置静态域 nextId等于1
private static int nextId = 1;
private String name;
private double salary;
private int id;
public Employee(String n, double s){
name = n;
salary = s;
id = 0;
}
//得到员工的名字 并返回
public String getName(){
return name;
}
//得到员工的工资 并返回
public double getSalary() {
return salary;
}
//得到员工的Id 并返回
public int getId(){
return id;
}
//下一个员工Id的方法
public void setId(){
id = nextId;
nextId++;
}
//得到下一个员工的Id 并返回
public static int getNextId(){
return nextId;
}
//测试Employee类 运行是否正确
public static void main(String[] args) {
Employee e = new Employee("Harry", 50000);
System.out.println(e.getName() + " " + e.getSalary());
}
}
输出结果为:
name=Tom,id=1,salary=40000.0
name=Dick,id=2,salary=60000.0
name=Harry,id=3,salary=65000.0
Next available id=4



