OOP Fundamentals · Coding problem
Payroll Without a Single Type Check
A free coding problem from the Polymorphism, Interfaces & Abstract Classes skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Solution.PAYROLL just calls e.monthlyPay() on every employee - no instanceof, no switch on a type field. Make that work by overriding monthlyPay() in each subclass:
| Class | Monthly pay |
|---|---|
Salaried | annualSalary / 12, rounded down |
Hourly | hours × rate for the first 160 hours; hours beyond 160 are paid at 1.5 × the rate (round the overtime amount down) |
Commissioned | base + percent% of sales, rounded down |
Commands: SALARIED <name> <annual>, HOURLY <name> <hours> <rate>, COMMISSION <name> <base> <sales> <percent>, PAYROLL.
Example
Input:
4
SALARIED ann 120000
HOURLY bob 170 20
COMMISSION cid 1000 50000 10
PAYROLL
Output:
hired ann
hired bob
hired cid
ann=10000, bob=3500, cid=6000 | total=19500
(Bob: 160 × 20 = 3200, plus 10 overtime hours × 30 = 300.)
In Python: Employee is an abstract base class with an @abstractmethod monthly_pay(), and the payroll loop calls it without any isinstance check. Round down with //.
Constraints
- At most 1000 commands; all values are non-negative and results fit in a
long.
How it's graded
- Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Polymorphism, Interfaces & Abstract Classes
Solve it Payroll Without a Single Type Check free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime