OOP in Practice · Episode 3 of 70 · OOP Foundations · Beginner · Java 21.0.12.1
The problem
You’re building the monthly payroll run for a small company, a good place to see inheritance in Java pay off and backfire. Staff are full-time (monthly salary), part-time (hourly) or contractors (daily, on an invoice). Each type has its own class with its own copy of the pay maths. When the tax rate changes, someone updates one copy and misses the others.
Your task: design the payroll classes so shared employee rules live in one place, and contractors are paid without inheriting rules that do not apply to them.
Requirements
- One run produces a payslip for every worker.
- Gross pay: salary; hourly rate × hours; or day rate × days.
- Employees lose 10% tax and 5% pension, calculated in one place.
- Contractors get their full gross, no deductions.
- Bad input (shift outside 0–12 hours, zero rate) is rejected and changes nothing.
- A new employee type is one new class, with no edits to deduction code.
Constraints and assumptions
- Single process, in memory; whole rupees, fractions dropped.
- The 10% and 5% rates are practice numbers, not tax law.
What this tests: inheritance, method overriding, abstract classes, final and sealed classes, the fragile base class problem
Inheritance in Java fits payroll when subclasses truly are the parent. An abstract Employee holds the shared deductions in one final payslip() method, and SalariedEmployee and HourlyEmployee override only grossPay(). Contractors are not employees, so they implement a small Payee interface instead of inheriting rules they would have to switch off.
Try it yourself first — hint
List what every employee shares and the one step that differs. Then ask: is a contractor an employee, or just someone the payroll pays?
Step 1: Identify the objects and responsibilities
| Class / interface | Responsibility | Key methods |
|---|---|---|
Payee (interface) |
Anyone the payroll run can pay. | payslip() |
Payslip (record) |
One immutable line of the run; works out net pay. | net(), toString() |
Employee (abstract, sealed) |
Shared employee rules: identity, tax and pension. | payslip() (final), grossPay() (abstract), kind() |
SalariedEmployee (final) |
Full-time pay from a monthly salary. | grossPay() |
HourlyEmployee (final) |
Part-time pay from logged shifts; validates each shift. | logHours(), logWeek(), grossPay() |
Contractor (final) |
Invoice pay with no deductions. Not an employee. | invoiceDays(), payslip() |
Step 2: The naive approach and why it breaks
class FullTimer {
String name; long monthlySalary;
long netPay() {
long tax = monthlySalary * 10 / 100;
long pension = monthlySalary * 5 / 100;
return monthlySalary - tax - pension;
}
}
class PartTimer {
String name; long hourlyRate; int hours;
long netPay() {
long gross = hourlyRate * hours;
long tax = gross * 12 / 100; // new rate: updated here only
long pension = gross * 5 / 100;
return gross - tax - pension;
}
}
class Contractor {
String name; long dayRate; int days;
long netPay() {
long gross = dayRate * days;
long tax = gross * 10 / 100; // pasted in: contractors are not withheld
return gross - tax;
}
}
This compiles cleanly with javac. That is the problem: every bug below is invisible to the compiler.
- The tax rate lives in three places. It was raised to 12% in
PartTimeronly, so equal gross pay gives unequal net pay. Contractorwithholds tax because its method was pasted from an employee class: a line nobody deleted.- No shared type. The payroll loop needs three lists or
instanceofchecks, edited for every new staff type. - Open fields:
hours = -3compiles. Encapsulation exists to stop this.
Step 3: The design
<<interface>> Payee
+ payslip(): Payslip
^ ^
implements | | implements
| |
<<abstract sealed>> Employee Contractor (final)
- id, name - id, name, dayRate, days
+ payslip(): Payslip {final} + invoiceDays(d)
# grossPay(): long {abstract} + payslip()
# kind(): String {abstract}
^ ^
extends | | extends
SalariedEmployee (final) HourlyEmployee (final)
- monthlySalary - hourlyRate, hours
# grossPay() + logHours(h), logWeek(...)
# grossPay()
Payslip (record): id, name, kind, gross, tax, pension, net()
Two relationships, two tools. Full-time and part-time staff get the same deductions and payslip: a real is-a relationship. So both extend an abstract Employee, which cannot be instantiated and forces subclasses to implement its abstract methods (Oracle: Abstract Methods and Classes).
Contractors share one thing: the run pays them. That is a role, so it becomes the Payee interface, the same move as in abstraction in OOP.
payslip() is a template method: it fixes the steps and leaves grossPay() to subclasses. It is final, as Refactoring.Guru suggests considering (Template Method), so no subclass can skip a deduction. More in Template Method pattern.
Employee is sealed: only classes in permits may extend it, and each must be final, sealed or non-sealed (Oracle: Sealed Classes, Java 21).
Step 4: The inheritance in Java solution (Java 21)
import java.util.List;
public class Main {
public static void main(String[] args) {
SalariedEmployee asha = new SalariedEmployee("E01", "Asha", 90_000);
HourlyEmployee ravi = new HourlyEmployee("E02", "Ravi", 400);
ravi.logWeek(8, 8, 6, 0, 4);
ravi.logHours(7);
Contractor meera = new Contractor("C01", "Meera", 6_000);
meera.invoiceDays(12);
List<Payee> run = List.of(asha, ravi, meera);
long totalNet = 0;
for (Payee p : run) {
Payslip slip = p.payslip();
System.out.println(slip);
totalNet += slip.net();
}
System.out.println("Total net paid: " + totalNet);
System.out.println("Ravi is an Employee: " + (ravi instanceof Employee));
Payee m = meera;
System.out.println("Meera is an Employee: " + (m instanceof Employee));
try {
ravi.logHours(-3);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
try {
new SalariedEmployee("E03", "Dev", 0);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
System.out.println("Ravi after rejected entry: " + ravi.payslip());
}
}
/** Anyone the payroll run pays. Employees and contractors both qualify. */
interface Payee {
Payslip payslip();
static long requirePositive(long value, String what) {
if (value <= 0) throw new IllegalArgumentException(what + " must be positive, got " + value);
return value;
}
}
/** One line of the payroll run. Amounts are whole rupees. */
record Payslip(String id, String name, String kind, long gross, long tax, long pension) {
long net() { return gross - tax - pension; }
@Override
public String toString() {
return String.format("%-3s %-5s %-10s gross %6d tax %5d pension %5d net %6d",
id, name, kind, gross, tax, pension, net());
}
}
/** Shared employee rules live here once. Only the classes in this file may extend it. */
abstract sealed class Employee implements Payee permits SalariedEmployee, HourlyEmployee {
static final int TAX_PERCENT = 10; // practice rates, not real tax law
static final int PENSION_PERCENT = 5;
private final String id;
private final String name;
protected Employee(String id, String name) {
this.id = id;
this.name = name;
}
/** Template method: final, so no subclass can skip a deduction. */
@Override
public final Payslip payslip() {
long gross = grossPay();
long tax = gross * TAX_PERCENT / 100;
long pension = gross * PENSION_PERCENT / 100;
return new Payslip(id, name, kind(), gross, tax, pension);
}
/** The one step that differs between employee types. */
protected abstract long grossPay();
protected abstract String kind();
}
final class SalariedEmployee extends Employee {
private final long monthlySalary;
SalariedEmployee(String id, String name, long monthlySalary) {
super(id, name);
this.monthlySalary = Payee.requirePositive(monthlySalary, "monthly salary");
}
@Override protected long grossPay() { return monthlySalary; }
@Override protected String kind() { return "full-time"; }
}
final class HourlyEmployee extends Employee {
private final long hourlyRate;
private int hours;
HourlyEmployee(String id, String name, long hourlyRate) {
super(id, name);
this.hourlyRate = Payee.requirePositive(hourlyRate, "hourly rate");
}
void logHours(int shiftHours) {
if (shiftHours < 0 || shiftHours > 12)
throw new IllegalArgumentException("shift hours must be 0-12, got " + shiftHours);
hours += shiftHours;
}
/** Calls logHours on purpose. Safe only because this class is final. */
void logWeek(int... shifts) {
for (int h : shifts) logHours(h);
}
@Override protected long grossPay() { return hourlyRate * hours; }
@Override protected String kind() { return "part-time"; }
}
/** Not an Employee: paid in full, no withholding, no pension. Shares the role, not the code. */
final class Contractor implements Payee {
private final String id;
private final String name;
private final long dayRate;
private int days;
Contractor(String id, String name, long dayRate) {
this.id = id;
this.name = name;
this.dayRate = Payee.requirePositive(dayRate, "day rate");
}
void invoiceDays(int d) {
if (d < 0) throw new IllegalArgumentException("days must be >= 0, got " + d);
days += d;
}
@Override
public Payslip payslip() {
return new Payslip(id, name, "contractor", dayRate * days, 0, 0);
}
}
super(id, name)runs the parent constructor; constructors are not inherited (Oracle: Inheritance, Oracle: Using super).@Overridemakes the compiler reject a misspelt override (Oracle: Overriding and Hiding Methods).- Final
payslip(), private fields: subclasses decide how pay is earned, never how it is taxed. Contractornever touchesEmployee; validation is a static helper onPayee.logWeek()callslogHours(). That is safe only because the class isfinal; see the fragile base class below.
Step 5: Run it and check the output
E01 Asha full-time gross 90000 tax 9000 pension 4500 net 76500 E02 Ravi part-time gross 13200 tax 1320 pension 660 net 11220 C01 Meera contractor gross 72000 tax 0 pension 0 net 72000 Total net paid: 159720 Ravi is an Employee: true Meera is an Employee: false Rejected: shift hours must be 0-12, got -3 Rejected: monthly salary must be positive, got 0 Ravi after rejected entry: E02 Ravi part-time gross 13200 tax 1320 pension 660 net 11220
Tested: Java OpenJDK 21.0.12.1 — java Main.java, 2026-11-16. Output above is copied from that run.
Ravi logged 33 hours at 400, so gross is 13,200. Meera pays no tax or pension because Contractor never inherited those rules. Both bad inputs are rejected, and Ravi’s last payslip matches his first.
We also appended class Intern extends Employee and class Senior extends SalariedEmployee and ran javac. Both failed: “class is not allowed to extend sealed class” and “cannot inherit from final SalariedEmployee”.
Why this design works
- One source of truth. A rate change is a one-line edit every employee type picks up.
- Substitutable subclasses. Any
Employeewas withheld, whatever the subclass: the Liskov substitution principle. - Encapsulation survives. Subclasses do not inherit
privatemembers (Oracle: Inheritance). - Is-a versus role. The run loops over
List<Payee>without knowing who is who, a preview of polymorphism.
Where inheritance hurts: the fragile base class
The fragile base class problem is when “seemingly safe modifications to a base class” break subclasses (Wikipedia: Fragile base class). Here an overtime tracker overrides logHours(). In v1 the base logWeek() calls logHours(); in v2 it adds hours directly.
public class Main {
public static void main(String[] args) {
int[] week = {8, 8, 8, 8, 8};
OvertimeTrackerV1 a = new OvertimeTrackerV1();
a.logWeek(week);
System.out.println("Base v1: timesheet=" + a.hours + "h, tracker saw=" + a.seen + "h");
OvertimeTrackerV2 b = new OvertimeTrackerV2();
b.logWeek(week);
System.out.println("Base v2: timesheet=" + b.hours + "h, tracker saw=" + b.seen + "h");
}
}
class TimesheetV1 {
int hours;
void logHours(int h) { hours += h; }
void logWeek(int[] days) { for (int d : days) logHours(d); } // self-use
}
class TimesheetV2 { // "harmless" refactor: same totals for TimesheetV2 itself
int hours;
void logHours(int h) { hours += h; }
void logWeek(int[] days) { for (int d : days) hours += d; } // no longer calls logHours
}
class OvertimeTrackerV1 extends TimesheetV1 {
int seen;
@Override void logHours(int h) { seen += h; super.logHours(h); }
}
class OvertimeTrackerV2 extends TimesheetV2 { // identical subclass code
int seen;
@Override void logHours(int h) { seen += h; super.logHours(h); }
}
Base v1: timesheet=40h, tracker saw=40h Base v2: timesheet=40h, tracker saw=0h
Tested: Java OpenJDK 21.0.12.1 — java Main.java on the snippet above, 2026-11-16.
Same subclass code, same base totals, yet the v2 tracker sees zero hours and overtime stops being paid. Nothing failed to compile. Joshua Bloch explains why: a subclass depends on its superclass’s implementation details (Java Magazine: favor composition over inheritance). Python behaves the same way (Python tutorial: Inheritance).
The defences here: a final template method, final leaf classes, a sealed base, and documented self-calls. Oracle adds that methods called from constructors should generally be final (Oracle: Writing Final Classes and Methods).
Trade-offs, edge cases and when not to use it
| Option | Use when | Cost |
|---|---|---|
| Abstract base + final template (this episode) | Subclasses share state and one algorithm | One parent; base changes reach every subclass |
Interface only (Payee) |
Unrelated classes share a role | Shared code repeated or delegated |
| Composition: a deduction policy object | Rules vary per person or at runtime | More objects to wire up |
Contractor extends Employee, deductions set to zero |
Never here | Breaks “every employee is withheld”; new deductions leak in |
One cost of sealed: a new employee type also edits the permits list in the base file. That is deliberate.
My recommendation: if classes share only a name and an id, use an interface. Use inheritance in Java when the shared logic is real, stable and owned by your team. See composition vs inheritance for the alternative.
Interview follow-up questions
A new rule says interns get no pension. How do you add interns?
Add final class Intern extends Employee and list it in permits. Pension now varies, so the fixed template no longer fits. One option is a protected hook, pensionPercent(), returning 5 by default and 0 for interns. Every hook is another place a subclass can bend the rules, though. My recommendation: once a second rule varies, pass a deduction policy object into the constructor instead.
Why not let Contractor extend Employee and override the deductions to zero?
Code holding an Employee expects tax withheld; a zeroed override breaks that, which is a Liskov violation. It is also fragile: add a health-insurance deduction to Employee later and contractors silently get it unless someone adds another override. Payee shares the role without the rules.
How would you unit test this hierarchy?
Test the deduction maths through each real subclass with known numbers: 90,000 salary gives 9,000 tax and 4,500 pension. Add shift boundaries (0, 12, −1, 13) and check a rejected call changes nothing. Because Employee is sealed, you cannot add a throwaway test subclass, so test real types or extract the maths into a pure function.
The same solution in Python
Python uses an abstract base class for Employee (Python docs: abc) and a Protocol for Payee. @final is checked by type checkers only, not at runtime (Python docs: typing.final).
Show the Python version
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Protocol, final
TAX_PERCENT, PENSION_PERCENT = 10, 5 # practice rates, not real tax law
@dataclass(frozen=True)
class Payslip:
id: str
name: str
kind: str
gross: int
tax: int
pension: int
@property
def net(self) -> int:
return self.gross - self.tax - self.pension
def __str__(self) -> str:
return (f"{self.id:<3} {self.name:<5} {self.kind:<10} gross {self.gross:6d} "
f"tax {self.tax:5d} pension {self.pension:5d} net {self.net:6d}")
class Payee(Protocol):
def payslip(self) -> Payslip: ...
def require_positive(value: int, what: str) -> int:
if value <= 0:
raise ValueError(f"{what} must be positive, got {value}")
return value
class Employee(ABC):
kind = "employee"
def __init__(self, id: str, name: str) -> None:
self._id, self._name = id, name
@final # checked by type checkers only, not at runtime
def payslip(self) -> Payslip:
gross = self._gross_pay()
return Payslip(self._id, self._name, self.kind, gross,
gross * TAX_PERCENT // 100, gross * PENSION_PERCENT // 100)
@abstractmethod
def _gross_pay(self) -> int: ...
@final
class SalariedEmployee(Employee):
kind = "full-time"
def __init__(self, id: str, name: str, monthly_salary: int) -> None:
super().__init__(id, name)
self._salary = require_positive(monthly_salary, "monthly salary")
def _gross_pay(self) -> int:
return self._salary
@final
class HourlyEmployee(Employee):
kind = "part-time"
def __init__(self, id: str, name: str, hourly_rate: int) -> None:
super().__init__(id, name)
self._rate, self._hours = require_positive(hourly_rate, "hourly rate"), 0
def log_hours(self, shift_hours: int) -> None:
if not 0 <= shift_hours <= 12:
raise ValueError(f"shift hours must be 0-12, got {shift_hours}")
self._hours += shift_hours
def log_week(self, *shifts: int) -> None:
for h in shifts:
self.log_hours(h)
def _gross_pay(self) -> int:
return self._rate * self._hours
@final
class Contractor: # not an Employee: satisfies Payee by shape alone
def __init__(self, id: str, name: str, day_rate: int) -> None:
self._id, self._name = id, name
self._rate, self._days = require_positive(day_rate, "day rate"), 0
def invoice_days(self, days: int) -> None:
if days < 0:
raise ValueError(f"days must be >= 0, got {days}")
self._days += days
def payslip(self) -> Payslip:
return Payslip(self._id, self._name, "contractor", self._rate * self._days, 0, 0)
asha = SalariedEmployee("E01", "Asha", 90_000)
ravi = HourlyEmployee("E02", "Ravi", 400)
ravi.log_week(8, 8, 6, 0, 4)
ravi.log_hours(7)
meera = Contractor("C01", "Meera", 6_000)
meera.invoice_days(12)
run: list[Payee] = [asha, ravi, meera]
for p in run:
print(p.payslip())
print("Total net paid:", sum(p.payslip().net for p in run))
print("Meera is an Employee:", isinstance(meera, Employee))
try:
Employee("E09", "Nobody") # type: ignore[abstract]
except TypeError as e:
print("Rejected:", type(e).__name__)
E01 Asha full-time gross 90000 tax 9000 pension 4500 net 76500 E02 Ravi part-time gross 13200 tax 1320 pension 660 net 11220 C01 Meera contractor gross 72000 tax 0 pension 0 net 72000 Total net paid: 159720 Meera is an Employee: False Rejected: TypeError
Tested: Python 3.13.18 — python3 main.py, 2026-11-16.
Practice: extend it yourself
- Add an
Internon a fixed stipend with 10% tax and no pension. Expected behaviour: pension 0 on the intern’s slip; other payslips unchanged. - Pay hours above 160 a month at 1.5×. Expected behaviour: 170 hours at 400 gives gross 70,000; only
HourlyEmployeechanges. - Make the overtime tracker wrap a timesheet instead of extending it. Expected behaviour: it reports 40h with both v1 and v2.
- Inheritance in Java models is-a: one direct superclass,
Objectby default. - Private members and constructors are not inherited; call the parent constructor with
super(...). @Overrideturns a misspelt override into a compile error.- A
finaltemplate method keeps shared rules out of subclasses’ reach. - If a type shares only a role, use an interface, not a base class.
Frequently Asked Questions
What is inheritance in Java?
Inheritance in Java lets one class extend another and reuse its public and protected members. The subclass can add members and override inherited methods. Every class has exactly one direct superclass, Object by default. Use it when the subclass truly is a kind of the parent.
Why can't a Java class extend more than one class?
Java avoids multiple inheritance of state: if two parents define fields, it is unclear which constructor or method wins. A class can still implement many interfaces, which gives multiple inheritance of type.
What is the fragile base class problem?
It is when a safe-looking change to a base class breaks a subclass, usually one that relies on how the base calls its own methods. In the demo above, a refactor stops logWeek() calling logHours(), and a tracker overriding logHours() silently sees zero hours.
When should I use composition instead of inheritance in Java?
Use composition for has-a or role relationships, for behaviour that changes at runtime, or when you do not control the parent class. Use inheritance when subclasses share real state and logic and the parent is designed for extension.
References
- Oracle Java Tutorials — Inheritance
- Oracle Java Tutorials — Overriding and Hiding Methods
- Oracle Java Tutorials — Using the Keyword super
- Oracle Java Tutorials — Writing Final Classes and Methods
- Oracle Java Tutorials — Abstract Methods and Classes
- Oracle Java Tutorials — Multiple Inheritance
- Oracle Java SE 21 Language Updates — Sealed Classes
- Java Magazine — Bloch: favor composition over inheritance
- Refactoring.Guru — Template Method
- Wikipedia — Fragile base class
- Python docs — Tutorial: Classes, Inheritance
- Python docs — abc: Abstract Base Classes
- Python docs — typing.final
