所以,我有一个OOP课程,我的任务是创建一个抽象的员工类,而不是为它制作更多的基类。这部分很简单,之后我不得不创建一个'Employee'类型的对象数组,并使用整个多态性来相应地启动所有基类。
这是我在主编中写的代码:
Scanner input = new Scanner (System.in);
int Size;
System.out.println("Enter Array Size");
Size = input.nextInt();
Employee [] Array = new Employee [Size];
int i;
int A;
System.out.println("Key: ");
System.out.println("Press 1 for Salaried Employee.");
System.out.println("Press 2 for Hourly Employee.");
System.out.println("Press 3 for Commision Employee.");
System.out.println("Press 4 for Base Plus Commision Employee.");
String Name;
String SSN;
double wage;
double hours;
double salary;
int Sales;
double CRate;
double BaseSalary;
for (i = 0; i < Array.length; i++ ) {
A = input.nextInt();
if (A == 1) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
Array [i] = new Salaried_Employee(Name, SSN);
System.out.println("Initial Earnings!" +Array[i].Earnings());
}
if (A == 2) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Wage!");
wage = input.nextDouble();
System.out.println("Enter hours!");
hours = input.nextDouble();
Array [i] = new Hourly_Employee (Name, SSN, wage, hours);
}
if (A == 3) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Sales!");
Sales = input.nextInt();
System.out.println("Enter Commision Rate!");
CRate = input.nextDouble();
Array [i] = new Comission_Employee (Name, SSN, Sales, CRate);
}
if (A == 4) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Sales!");
Sales = input.nextInt();
System.out.println("Enter Commision Rate!");
CRate = input.nextDouble();
System.out.println("Define the base salary");
BaseSalary = input.nextDouble();
Array [i] = new BassPlus_CommEmployee (Name, SSN, Sales, CRate, BaseSalary);
}
}
现在我必须通过Array List做同样的事情。我已经搜索了这个问题的生命,但我不知道如何创建一个Employee类型的ArrayList。
请帮助!!
答案 0 :(得分:4)
List<Employee> employeeList = new ArrayList<Employee>();
编辑:
employeeList.add(new BassPlus_CommEmployee (Name, SSN, Sales, CRate, BaseSalary));
employeeList.add(new Hourly_Employee (Name, SSN, wage, hours));
等
我假设员工是Superclass
。好吧,我认为这是因为您在代码中使用了这个确切的片段。
答案 1 :(得分:0)
ArrayList
是包含其他Object
的{{1}}。
因此,您必须调用方法来替换您使用Object
进行的分配。
Array
可以转置为array[i] = new Employee();
,例如
然后,您需要找到如何arraylist.add(new Employee())
转置值get
不要忘记不使用null Employee e = array[i]
。