java - Java中的instanceof和数组

标签 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 循环中更新 = 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/

相关文章:

java - 识别 Java 程序中变量的状态

java - 在数组中搜索特定参数 Java

java - 为什么 RuntimeException 不能从 Throwable 分配?

java - JAVA中动态加载一个类-Anomaly

java - 在 Json 字符串中进行类型检查

java - 避免将 InstanceOf 与访问者模式一起使用 - Java

Java 8 可选 : choose between two possibly null values

java - JAXB:处理根元素

java - 如何使用 ModelAndview 将模型(bean)值从 Controller 传递到 jsp 页面?

java instanceof运算符和类返回方法