我有一个员工班:
public abstract class Employee {
private String firstName;
private String lastName;
private int joinYear, joinMonth, joinDay;
LocalDate startDate;
static int idCounter=0;
private double employeeId;
private double numEmployees;
Employee[] employeeArray = new Employee[10];
private double monthlyEarnings;
// constructor
public Employee(String first, String last, int year, int month, int day) {
firstName = first;
lastName = last;
joinYear=year;
joinMonth=month;
joinDay=day;
startDate= new LocalDate(joinYear, joinMonth, joinDay);
this.monthlyEarnings=0;
this.setEmployeeId(idCounter);
employeeArray[idCounter]=this;
idCounter++;
numEmployees++;
}
}
如上所示,在构造函数中,创建employee对象时,会将其添加到employeeArray:employeeArray[idCounter]=this;
然后,当我尝试在main方法中访问数组的成员时,我收到错误“employeeArray无法解析为变量”
public class Test {
// test Employee hierarchy
public static void main(String args[]) {
Employee Employee1 = new Employee("John", "Smith", 1997, 8, 20);
Employee Employee2 = new Employee("Bob", "Oak", 1999, 6, 20);
System.out.println(employeeArray[1]); //error here
}
}
答案 0 :(得分:2)
显然employeeArray
超出了主要范围。您需要使用(instance of Employee).employeeArray
引用它。
然而,由于您的类Employee的逻辑被破坏,这在您的情况下是无关紧要的。问题是,idCounter
的所有实例都不会共享您的employeeArray
和Employee
变量。相反,每个Employee实例都有自己的列表和计数器(您似乎并不想要)。
事实上,您需要在类本身内创建一个{strong>静态数组Employee
。在我看来,使用List<Employee>
代替Employee[]
更合适,因为您(可能)事先并不知道您需要存储多少员工。
以下是你应该围绕
设计课程的内容public class Employee {
private static List<Employee> employees = new ArrayList<>();
// Your instance fields here
int employeeId;
public Employee() {
// Constructor stuff
this.employeeId = employees.size();
employees.add(this); // Add the new employee to the list
}
public static List<Employee> getEmployees() {
return employees;
}
}
答案 1 :(得分:0)
此错误为真:
employeeArray无法解析为变量
您的测试中未定义employeeArray
。
您必须从Employee
课程中获取该实例。
示例:
System.out.println(Employee1.employeeArray[1]);