在数组列表中使用多态时调用子方法 [英] Calling child methods while using polymorphism in an arraylist
问题描述
我有一个正在处理继承和多态性的小项目.我有一个Employee类型的ArrayList,它同时包含Hourly和Salary雇员对象.我希望能够使用for循环在Hourly类中调用calcPay
函数,条件是Employee类型的ArrayList中的对象是Hourly雇员.线
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());
给出错误The method calcPay() is undefined for type employee
.您如何向下转换对象?我到过很多论坛,但找不到一个允许我内联或不编写必须包含在所有Employee子类中的抽象方法的选项.任何见识将不胜感激.
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;
}
}
推荐答案
即使您确定e的类型为Hourly,您仍需要强制转换它并使用Hourly
类型调用calcPay()
,因为e是Employee类型,而Employee不知道任何calcPay()
方法,因为您已将calcPay()
定义为仅Hourly
类方法.
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());
}
如果希望所有Employee实例都可以访问calcPay(),则需要在Employee类中将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.
已更新:
if(e instanceof Hourly)
{
System.out.println("Wage: " ((Hourly)e).calcPay());
}
这篇关于在数组列表中使用多态时调用子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!