我有一个小项目,我正在处理继承和多态性。我有一个 Employee 类型的 ArrayList,其中包含 Hourly 和 Salary 员工对象。我希望能够使用 for 循环来调用calcPay
Hourly 类中的函数,前提是 Employee 类型的 ArrayList 中的对象是 Hourly 员工。线
System.out.println("Wage: " e.calcPay());
给出错误The method calcPay() is undefined for type employee
。你如何使对象失望?我查看了很多论坛,但找不到允许我内联或不编写必须包含在 Employee 的所有子类中的抽象方法的选项。任何见解将不胜感激。
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;
}
}