Reputation: 462
I have a small project that I'm working with inheritance and polymorphism. I have an ArrayList of type Employee that contains both Hourly and Salary employee objects. I would like to be able to use a for loop to call a calcPay
function in the Hourly class provided the object in the ArrayList of type Employee is an Hourly employee. The line
System.out.println("Wage: " e.calcPay());
Gives the error The method calcPay() is undefined for type employee
. How do you downcast the object? I've looked in a lot of forums and I couldn't find an option that would allow me to do it inline or without writing an abstract method that I'd have to include in all of the child classes of Employee. Any insight would be much appreciated.
public class Driver {
public static void main(String[] args) {
ArrayList<Employee> list = new ArrayList<Employee>();
Employee emp1 = new Hourly("Hourly Emp", "123 E Center", "555-555-5555", 00001, "123-45-6789", 12.75);
Employee emp2 = new Salary("Salary Emp", "123 E Center", "555-555-5555", 00001, "123-45-6789");
list.add(emp1);
list.add(emp2);
for(Employee e : list){
if(e instanceof Hourly)
{
System.out.println("Wage: " e.calcPay());
}
}
}
public abstract class Employee {
private String name, address, phone, ssn;
private int empNo;
Employee(String name, String address, String phone, int empNo, String ssn)
{
this.name = name;
this.address = address;
this.phone = phone;
this.empNo = empNo;
this.ssn = ssn;
}
}
public class Hourly extends Employee {
private double wage;
Hourly(String name, String address, String phone, int empNo, String ssn, double wage)
{
super(name, address, phone, empNo, ssn);
this.wage = wage;
}
public double calcPay(double hours)
{
return wage * hours;
}
}
Upvotes: 4
Views: 3501
Reputation: 66677
Even though you are making sure e is of type Hourly, you still need to cast it and use Hourly
type to call calcPay()
because e is of type Employee and Employee is not aware of any calcPay()
method because you have defined calcPay()
as only Hourly
class method.
if(e instanceof Hourly)
{
Hourly hourly = (Hourly)e;
System.out.println("Wage: " hourly.calcPay());
}
If you want calcPay() accessible for all Employee instances, you need to define calcPay() as abstract method in Employee class, then you can avoid casting.
Updated:
if(e instanceof Hourly)
{
System.out.println("Wage: " ((Hourly)e).calcPay());
}
Upvotes: 2
Reputation: 198581
If calcPay
is supported for all Employee
s, then it should be an abstract method in Employee
, which will let you call it without having to downcast at all.
Upvotes: 2