这里是一个开始:
import java.math.BigDecimal;
import java.util.*;
abstract class Employee {
Employee(String name) {
this.name = name;
}
final String name;
}
class SalariedEmployee extends Employee {
SalariedEmployee(String name, BigDecimal salary) {
super(name);
this.salary = salary;
}
public String toString() {
return getClass().getSimpleName() + " " + name + " " + salary;
}
final BigDecimal salary;
}
class HourlyEmployee extends Employee {
HourlyEmployee(String name, BigDecimal hourlyRate) {
super(name);
this.hourlyRate = hourlyRate;
}
public String toString() {
return getClass().getSimpleName() + " " + name + " " + hourlyRate;
}
final BigDecimal hourlyRate;
}
class CommissionEmployee extends Employee {
CommissionEmployee(String name, BigDecimal percentage) {
super(name);
this.percentage = percentage;
}
public String toString() {
return getClass().getSimpleName() + " " + name + " " + percentage + "%";
}
final BigDecimal percentage;
}
class Manager {
public String toString() {
return Arrays.asList(employees).toString();
}
Employee[] employees = new Employee[] { new SalariedEmployee("joe", BigDecimal.valueOf(4567.89)),
new HourlyEmployee("mary", BigDecimal.valueOf(12.34)),
new CommissionEmployee("bob", BigDecimal.valueOf(12.34)) };
}
public class Main {
public static void main(String[] args) {
System.out.println(new Manager());
}
}
听起来EmployeeDriver包含(公会)EmployeeManager。司机给出了一个菜单,其中包括获得薪水等选项。驱动程序将在Manager上调用“getSalary()”,管理器将调用其所有员工的“getSalary()”多态函数(像你说的那样循环遍历数组)。你没有得到什么? – John3136 2012-02-07 04:15:20
好像我需要列出所有HoulyEmployees,包括他们的employeeNumber,firstname,lastname,hoursworked等。如果我循环访问数组,首先我如何列出所有这些东西,其次我如何才能获得HOurlyEmployees,而不是薪水或Commision – kel 2012-02-07 18:22:23