[英]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.