带有数组Java的instanceof

时间:2016-03-15 01:34:00

标签: java instanceof

我正在使用一个名为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循环中)

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与对象本身相关联。有谁知道我怎么做到这一点? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

  

它只打印原始Employee类的属性,   不是来自子类。

您需要覆盖子类中的^以包含新属性。