這裏是一個開始:
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