Payroll with Inheritance and Method Overriding
Problem
Each input line is employee NAME BASE, intern NAME STIPEND or manager NAME BASE BONUS. An employee and an intern are paid the amount given. A manager is paid BASE plus BONUS. Print NAME and the pay for each line, then a last line Total X with the sum of all pay. Use a parent class and a child class that overrides the pay method.
Constraints
- 1 <= lines <= 10^4
- pay values fit in 10^12
Examples
Input
employee ravi 5000 manager asha 9000 1500
Output
ravi 5000 asha 10500 Total 15500
Solutions
The Manager class reuses the parent's pay() with super and adds the bonus. The loop only calls pay(); it does not check the type.
/*
* Problem : Process commands line by line.
* Input : Several lines.
* Output : Pay lines and a total.
* Approach: Parent class and an overriding child.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: The parent class holds the base pay. Pay is the base amount by default.
static class Staff {
protected final String name;
protected final long base;
Staff(String name, long base) {
this.name = name;
this.base = base;
}
long pay() {
return base;
}
}
// Step 2: A manager gets the base pay plus a bonus. It replaces (overrides) pay().
static class Manager extends Staff {
private final long bonus;
Manager(String name, long base, long bonus) {
super(name, base);
this.bonus = bonus;
}
@Override
long pay() {
return super.pay() + bonus;
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
java.util.List<Staff> people = new java.util.ArrayList<>();
for (String line : lines) {
String[] parts = line.split(" ");
// Step 3: Make a Manager for a manager line. Other lines are plain Staff.
if (parts[0].equals("manager")) {
people.add(new Manager(parts[1], Long.parseLong(parts[2]), Long.parseLong(parts[3])));
} else {
people.add(new Staff(parts[1], Long.parseLong(parts[2])));
}
}
// Step 4: Call pay() on each person. Java picks the right version at run time.
String[] output = new String[people.size() + 1];
long total = 0;
for (int i = 0; i < people.size(); i++) {
long amount = people.get(i).pay();
output[i] = people.get(i).name + " " + amount;
total += amount;
}
output[people.size()] = "Total " + total;
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (1)
- How does a child reuse the parent's method?