2016-03-15 48 views
0

我正在使用一個名爲Employee的類和兩個名爲SalariedEmployee和HourlyEmployee的子類。在我的代碼的這部分中,我試圖測試一個數組中的Employee是SalariedEmployee還是HourlyEmployee。但是,它僅從最初的Employee類打印屬性,而不是從子類打印。instanceof數組Java

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與對象本身關聯起來。有誰知道我該怎麼做? 感謝您的幫助。

+2

不應該'while(loop = true)'是'while(循環)'(沒有可能有害的賦值)或'for(;;)'(簡單的無限循環)? – MikeCAT

+0

是的,這是我的一個粗心的錯誤,但它仍然不能回答更大的問題。 – mellerlite

+0

您不需要檢查'instanceof SalariedEmployee'等僱員[index] .toString()'和'((SalariedEmployee)employees [index]).toString()'調用完全相同的方法。 –

回答

2

它只是從原來的員工一流的印刷屬性, 不從子類。

您需要在子類中覆蓋toString()以包含新屬性。

+0

如果這就是你所需要的,那麼你不需要執行'instanceof'並投射。如果員工實例知道如何打印自己,則調用方法不需要進行區分。多態性之美。 – Thilo

+0

@Thilo我已經在子類中的toString方法之前添加了Override,它仍然不起作用。 – mellerlite

+0

請在問題中包含所有'toString'方法的實現。 – Thilo