[英]Java | calling method of a child class
我有一个名为 HourlyEmployee 的 class,它扩展了一个名为 Employee 的 class。
HourlyEmployee 有一个 getHoursWorked 方法,在 Employee class 中不存在。
现在在我的主要 class 中,我有一系列不同类型的员工(小时工和薪水),我正在尝试运行一个 for 循环来获取每个 HourlyEmployee 的工作时间。
有人可以告诉我我在这里做错了什么吗?
for (int i = 0; i < employees.length; i++) {
if (employees[i] instanceof HourlyEmployee) {
if (employees[i].getHoursWorked() > 80) {
System.out.println(employees[i].getFullName() + ": " + (employees[i]getHoursWorked() - 80));
}
}
}
当我尝试在 if 语句和 println 中调用 getHoursWorked 时,它会抛出错误。
如果需要,我可以提供其他上下文,请告诉我。 谢谢。
您需要将employees[i]
转换为HourlyEmployee
。
for (int i = 0; i < employees.length; i++) {
if (employees[i] instanceof HourlyEmployee) {
HourlyEmployee employee = (HourlyEmployee) employees[i];
if (employee.getHoursWorked() > 80) {
System.out.println(employee.getFullName() + ": " + (employee.getHoursWorked() - 80));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.