我正在使用一个名为 Employee 的类和两个名为 SalariedEmployee 和 HourlyEmployee 的子类。在我的代码的这一部分中,我试图测试数组中的 Employee 是否是 SalariedEmployee 或 HourlyEmployee。但是,它仅打印原始 Employee 类的属性,而不是子类的属性。
case 2: {
for(int index = 0; index < employees.length; index++ ) {
System.out.println( employees[index] + "\n" );
if(employees[index] instanceof SalariedEmployee) {
SalariedEmployee aSalariedEmployee = (SalariedEmployee) employees[index];
System.out.println( aSalariedEmployee.toString() );
}
else if(employees[index] instanceof HourlyEmployee) {
HourlyEmployee anHourlyEmployee = (HourlyEmployee) employees[index];
System.out.println( anHourlyEmployee.toString() );
}
else {
System.out.println( " " );
}
}
System.out.println( " " );
break;
}
这是我的代码的数据收集部分:(编辑:在 while 循环中更新 = to ==)
int typeEmployee;
boolean loop = true;
OUTER:
while (loop == true) {
System.out.print( "Enter 1 if the Employee is Salaried, 2 if Hourly: " );
typeEmployee = info.nextInt();
switch (typeEmployee) {
case 1:
System.out.print( "Enter the Employee's Salary (with no commas): " );
float annSalary = info.nextFloat();
SalariedEmployee aSalariedEmployee = new SalariedEmployee(annSalary);
aSalariedEmployee.setAnnualSalary(annSalary);
break OUTER;
case 2:
System.out.print( "Enter the Employee's Hourly Pay Rate: " );
float hPRate = info.nextFloat();
System.out.print( "Enter the number of Hours Worked in a week: " );
float hWorked = info.nextFloat();
HourlyEmployee anHourlyEmployee = new HourlyEmployee(hPRate, hWorked);
anHourlyEmployee.setHourlyPayRate(hPRate);
anHourlyEmployee.setHoursWorked(hWorked);
break OUTER;
default:
System.out.println( "Invalid Option." );
break;
}
}
我觉得我在这里缺少的是我需要以某种方式将 typeEmployee 与对象本身关联起来。有谁知道我该怎么做? 感谢您的帮助。
最佳答案
it is only printing the attributes from the original Employee class, not from the subclasses.
您需要重写子类中的toString()
以包含新属性。
关于java - Java中的instanceof和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001154/