Pay Slip with Abstract Class
A school event hires temporary helpers and pays them by the hour. Each pay slip should show the helper's name together with the total amount earned.
Your task is to model this using an abstract base class. The final output should be a string in the format "Name earns Total", where Total is hours * rate.
For example, if the input is "Nina", 3 hours, and a rate of 20, the result should be "Nina earns 60". If the input is "Raka", 5 hours, and a rate of 15, the result should be "Raka earns 75".
This challenge focuses on abstract classes. The shared employee behavior should live in the parent class, while the actual pay calculation should be implemented by a concrete child class.
Example Input & Output
The concrete subclass calculates pay from hours and rate.
Even a one-hour shift still uses the same abstract-class structure.
The slip format stays the same while the total changes with the inputs.
Algorithm Flow

Solution Approach
This problem is a good demonstration of why abstract classes exist. The parent class can define behavior that is shared by all employees, while leaving one detail unfinished for subclasses to provide.
Here, every employee has a name, and every pay slip should follow the same sentence format. That shared part belongs nicely in an abstract Employee class. But the exact pay calculation can be defined by a child class such as HourlyEmployee.
A strong design is to let the abstract class define an abstract method like calculatePay(), then let the parent also define a regular method such as getSlip() that calls that abstract method:
Then the child class implements calculatePay() using the hourly rate and hours worked. That is what makes the parent abstract: it defines the shape of the behavior, but not the final formula.
This pattern is useful because the shared output format stays in one place. If different employee types were added later, each child class could provide its own pay calculation while still reusing the same getSlip() logic from the abstract parent.
The runtime is O(1). The main lesson is how an abstract class can mix shared implementation with one required method that subclasses must complete.
Best Answers
abstract class Employee {
protected String name;
public Employee(String name) {
this.name = name;
}
public abstract int calculatePay();
public String getSlip() {
return String.format("%s earns %d", name, calculatePay());
}
}
class HourlyEmployee extends Employee {
private int hours;
private int rate;
public HourlyEmployee(String name, int hours, int rate) {
super(name);
this.hours = hours;
this.rate = rate;
}
@Override
public int calculatePay() {
return hours * rate;
}
}
class Solution {
public static String buildPaySlip(String name, int hours, int rate) {
return new HourlyEmployee(name, hours, rate).getSlip();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
