Different employees are paid in different ways; let each class work out its own pay.
What to build
A program that prints each employee's pay and the total.
Requirements
- Write an abstract class
Employeewith anameand an abstractpay(): number, and subclassesSalaried(a monthly salary) andHourly(a rate and hours, with hours over 40 paid at 1.5 times the rate). - Print
NAME: PAYfor each employee (two decimal places), thentotal: T.
Input
Line 1: n. Then n lines: salaried NAME SALARY or hourly NAME RATE HOURS.
Output
n lines, then the total.
Constraints
1 ≤ n ≤ 50; numbers are not negative.
Example
Input:
3
salaried Ada 5000
hourly Alan 20 45
hourly Grace 30 10
Output:
Ada: 5000.00
Alan: 950.00
Grace: 300.00
total: 6250.00
Why it works
Code that adds up the payroll calls pay() on every employee without knowing their kind, and adding a new kind of employee needs only a new subclass.
Examples
Example 1 · Input
3 salaried Ada 5000 hourly Alan 20 45 hourly Grace 30 10
Expected output
Ada: 5000.00 Alan: 950.00 Grace: 300.00 total: 6250.00
Example 2 · Input
1 hourly Rina 12.5 40
Expected output
Rina: 500.00 total: 500.00
Hints
Hint 1
abstract class Employee { constructor(readonly name: string) {} abstract pay(): number }.
Hint 2
Hours over 40 are paid at 1.5 times the rate.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
abstract class Employee {
constructor(readonly name: string) {}
abstract pay(): number;
}
class Salaried extends Employee {
constructor(name: string, private salary: number) {
super(name);
}
pay(): number {
return this.salary;
}
}
class Hourly extends Employee {
constructor(name: string, private rate: number, private hours: number) {
super(name);
}
pay(): number {
const extra = Math.max(0, this.hours - 40);
return (this.hours - extra) * this.rate + extra * this.rate * 1.5;
}
}
const n = Number(read());
const staff: Employee[] = [];
for (let i = 0; i < n; i++) {
const [kind, name, a, b] = read().split(" ");
staff.push(kind === "salaried" ? new Salaried(name, Number(a)) : new Hourly(name, Number(a), Number(b)));
}
let total = 0;
for (const e of staff) {
const p = e.pay();
total += p;
console.log(e.name + ": " + p.toFixed(2));
}
console.log("total: " + total.toFixed(2));