I have a class called HourlyEmployee that extends a class called Employee.
The HourlyEmployee has a method to getHoursWorked that does not exist in the Employee class.
Now in my main class I have an array of different types of employees (both hourly and salary) and I am trying to run a for loop that grabs the hours worked of each HourlyEmployee.
Can someone tell me what I am doing wrong here?
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));
}
}
}
It throws errors when I attempt to call getHoursWorked in the if statement as well as the println.
I can provide additional context if needed, just let me know. Thanks.
You need to cast employees[i]
to 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));
}
}
}