Object-Oriented Programming — The Big Picture
Introduction
Procedural Programming ended with a payroll that works and one problem it could not fix: the data and the functions that use it live apart. calculate_gross_pay(hours, rate) takes two numbers and has no idea they belong to an employee, because the program has no idea what an employee is. Anyone can call it with any numbers, sensible or not.
Object-oriented programming, usually shortened to OOP, answers this with one idea: the object, a self-contained unit that keeps some data together with the code that works on that data. Python's documentation describes it in one sentence: "Objects have internal state and support methods that query or modify this internal state in some way."
What follows is the big picture: the same payroll rebuilt with objects, what changes, and where objects are the wrong tool. Each idea gets its full treatment later, starting with Classes and Objects — Blueprint vs Instance.
What Is Object-Oriented Programming?
Object-oriented programming builds a program out of objects, each standing for one thing in the problem you are solving. In the payroll, every employee becomes an object, and each object brings together three things:
- State, the data it holds. Alice's object holds her name and her hourly rate, 35.00.
- Behavior, what it can do through its methods. A method is a function that belongs to an object: Alice's object can work out her gross pay for a week.
- Identity. Each object is its own thing, so two employees with the same name and the same rate are still two different objects.
Notice what is not in Alice's object: her hours. They change every week, so PayrollSystem passes each week's hours in with its call, and the object works out the pay for them. Deciding what an object should keep and what it should be given is a large part of design.
The bigger change is in how you think about the problem. With procedural code you ask which steps the program must take, write a function for each, and pass the data between them. With objects you first ask which things exist in the problem and what each one knows and does, and then let them work together by calling each other's methods. For the payroll that gives an Employee that knows how it is paid, and a PayrollSystem that asks each employee for a pay stub.
A company can be described both ways. One description is a list of procedures, hire someone, run the payroll, file the taxes, with records handed from one procedure to the next. The other is the people and departments in it, each keeping its own records and doing its own job, and asking the others for what it needs. In the second, the payroll office does not work out everyone's pay itself; it asks each person's record for a pay stub. Object-oriented code is organised like the second description, which is why it tends to read like the problem it solves.
The Four Pillars at a Glance
Four ideas carry most of object-oriented design, and they are often called its four pillars. Each gets its own lesson later in this course. Here is what each one means for the payroll.

Encapsulation keeps an object's data together with the methods that work on it, and keeps other code from changing that data directly. HourlyEmployee checks its rate once, when the object is made, so HourlyEmployee("Alice", -50) stops with an error and no object is made. How strictly this is enforced depends on the language. In Java the rate is private, and the compiler refuses any outside code that tries to change it. Python has no such rule; its tutorial says plainly that "“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python." The underscore in _hourly_rate is a convention that asks other programmers to leave the value alone. Code that ignores it can set alice._hourly_rate = -50, and Alice's next 45 hours then come to minus 2375.00. Encapsulation — Data Hiding Done Right covers this in full.
Abstraction means callers use a simple method and never see how the work is done. PayrollSystem calls generate_pay_stub(45) and gets a pay stub back. It never sees the overtime threshold, the multiplier or the arithmetic. Abstraction — Hiding Complexity takes this further.
Inheritance builds a new class from an existing one. HourlyEmployee and SalariedEmployee both extend Employee, so they share its name, its tax rule and its generate_pay_stub method, written once, and each adds what is its own. Inheritance — Code Reuse & Hierarchies covers it.
Polymorphism means one call can run different code depending on the object that receives it. PayrollSystem asks every employee for a pay stub in exactly the same way. An HourlyEmployee pays overtime past 40 hours, and a SalariedEmployee returns its weekly salary whatever the hours, with no chain of if statements on the employee's type. Polymorphism — Compile-Time vs Runtime explains how it works.
The Payroll, Rebuilt with Objects
Here is the payroll from Procedural Programming once more, with the same employees, the same overtime rule and the same tax, now built from objects. Diana is paid a salary, as in the second program of Procedural Programming: 55.00 an hour over a year of 2080 hours is the 114,400.00 a year her object holds. Each kind of employee is a class, and each employee is an object of its class.
# OOP style: the same payroll, modeled as collaborating objects
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class PayStub:
"""A pay stub: one employee's pay for the week, as a small value object."""
name: str
gross: float
tax: float
net: float
class Employee(ABC):
"""What every employee is and can do; each kind fills in how it is paid."""
TAX_RATE = 0.20 # shared by every kind, written once
def __init__(self, name: str) -> None:
self._name = name # the underscore marks it internal, by convention
@property
def name(self) -> str:
return self._name
@abstractmethod
def calculate_gross_pay(self, hours: int) -> float:
"""Polymorphism: each kind of employee works out its own gross pay."""
@abstractmethod
def has_overtime(self, hours: int) -> bool:
"""Each kind also says for itself whether a week's hours count as overtime."""
def calculate_tax(self, gross_pay: float) -> float:
"""Inheritance: the tax rule is shared by every kind."""
return gross_pay * self.TAX_RATE
def generate_pay_stub(self, hours: int) -> PayStub:
"""Abstraction: callers get a pay stub without knowing how it is worked out."""
gross = self.calculate_gross_pay(hours)
tax = self.calculate_tax(gross)
return PayStub(self._name, gross, tax, gross - tax)
class HourlyEmployee(Employee):
OVERTIME_THRESHOLD = 40
OVERTIME_MULTIPLIER = 1.5
def __init__(self, name: str, hourly_rate: float) -> None:
super().__init__(name)
# Encapsulation: the rate is checked once, here
if hourly_rate < 0:
raise ValueError("Hourly rate cannot be negative")
self._hourly_rate = hourly_rate
def calculate_gross_pay(self, hours: int) -> float:
if hours < 0:
raise ValueError("Hours cannot be negative")
if hours > self.OVERTIME_THRESHOLD:
regular = self.OVERTIME_THRESHOLD * self._hourly_rate
overtime = ((hours - self.OVERTIME_THRESHOLD) * self._hourly_rate
* self.OVERTIME_MULTIPLIER)
return regular + overtime
return hours * self._hourly_rate
def has_overtime(self, hours: int) -> bool:
return hours > self.OVERTIME_THRESHOLD
class SalariedEmployee(Employee):
def __init__(self, name: str, annual_salary: float) -> None:
super().__init__(name)
if annual_salary < 0:
raise ValueError("Salary cannot be negative")
self._annual_salary = annual_salary
def calculate_gross_pay(self, hours: int) -> float:
return self._annual_salary / 52 # the same every week, whatever the hours
def has_overtime(self, hours: int) -> bool:
return False # a salary has no overtime
class PayrollSystem:
def run_payroll(self, employees: list[Employee], hours_list: list[int]) -> None:
total_gross = 0.0
total_tax = 0.0
total_net = 0.0
overtime_count = 0
for employee, hours in zip(employees, hours_list):
# The same calls for every employee; each object answers in its own way
stub = employee.generate_pay_stub(hours)
total_gross += stub.gross
total_tax += stub.tax
total_net += stub.net
if employee.has_overtime(hours):
overtime_count += 1
print(f"{stub.name}: Gross=${stub.gross:.2f}, "
f"Tax=${stub.tax:.2f}, Net=${stub.net:.2f}")
print("\nPayroll Summary:")
print(f"Total Gross: ${total_gross:.2f}")
print(f"Total Tax: ${total_tax:.2f}")
print(f"Total Net: ${total_net:.2f}")
print(f"Overtime Employees: {overtime_count}")
# Objects model the entities: each employee holds its own data
employees = [
HourlyEmployee("Alice", 35.0),
HourlyEmployee("Bob", 42.0),
HourlyEmployee("Charlie", 28.0),
SalariedEmployee("Diana", 114_400.0),
]
hours = [45, 38, 52, 40]
PayrollSystem().run_payroll(employees, hours)import java.util.List;
import java.util.Locale;
// OOP style: the same payroll, modeled as collaborating objects
// A pay stub: one employee's pay for the week, as a small value object
record PayStub(String name, double gross, double tax, double net) {}
// What every employee is and can do; each kind fills in how it is paid
abstract class Employee {
static final double TAX_RATE = 0.20; // shared by every kind, written once
private final String name;
protected Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
// Polymorphism: each kind of employee works out its own gross pay
public abstract double calculateGrossPay(int hours);
// Each kind also says for itself whether a week's hours count as overtime
public abstract boolean hasOvertime(int hours);
// Inheritance: the tax rule is shared by every kind
public double calculateTax(double grossPay) {
return grossPay * TAX_RATE;
}
// Abstraction: callers ask for a pay stub without knowing how it is worked out
public PayStub generatePayStub(int hours) {
double gross = calculateGrossPay(hours);
double tax = calculateTax(gross);
return new PayStub(name, gross, tax, gross - tax);
}
}
class HourlyEmployee extends Employee {
static final int OVERTIME_THRESHOLD = 40;
static final double OVERTIME_MULTIPLIER = 1.5;
// Encapsulation: the rate is checked once, here, and nothing outside can change it
private final double hourlyRate;
public HourlyEmployee(String name, double hourlyRate) {
super(name);
if (hourlyRate < 0) {
throw new IllegalArgumentException("Hourly rate cannot be negative");
}
this.hourlyRate = hourlyRate;
}
@Override
public double calculateGrossPay(int hours) {
if (hours < 0) {
throw new IllegalArgumentException("Hours cannot be negative");
}
if (hours > OVERTIME_THRESHOLD) {
double regular = OVERTIME_THRESHOLD * hourlyRate;
double overtime =
(hours - OVERTIME_THRESHOLD) * hourlyRate * OVERTIME_MULTIPLIER;
return regular + overtime;
}
return hours * hourlyRate;
}
@Override
public boolean hasOvertime(int hours) {
return hours > OVERTIME_THRESHOLD;
}
}
class SalariedEmployee extends Employee {
private final double annualSalary;
public SalariedEmployee(String name, double annualSalary) {
super(name);
if (annualSalary < 0) {
throw new IllegalArgumentException("Salary cannot be negative");
}
this.annualSalary = annualSalary;
}
@Override
public double calculateGrossPay(int hours) {
return annualSalary / 52; // the same every week, whatever the hours
}
@Override
public boolean hasOvertime(int hours) {
return false; // a salary has no overtime
}
}
class PayrollSystem {
public void runPayroll(List<Employee> employees, int[] hoursList) {
double totalGross = 0.0;
double totalTax = 0.0;
double totalNet = 0.0;
int overtimeCount = 0;
for (int i = 0; i < employees.size(); i++) {
Employee employee = employees.get(i);
// The same calls for every employee; each object answers in its own way
PayStub stub = employee.generatePayStub(hoursList[i]);
totalGross += stub.gross();
totalTax += stub.tax();
totalNet += stub.net();
if (employee.hasOvertime(hoursList[i])) {
overtimeCount++;
}
System.out.printf(Locale.ROOT, "%s: Gross=$%.2f, Tax=$%.2f, Net=$%.2f%n",
stub.name(), stub.gross(), stub.tax(), stub.net());
}
System.out.println("\nPayroll Summary:");
System.out.printf(Locale.ROOT, "Total Gross: $%.2f%n", totalGross);
System.out.printf(Locale.ROOT, "Total Tax: $%.2f%n", totalTax);
System.out.printf(Locale.ROOT, "Total Net: $%.2f%n", totalNet);
System.out.println("Overtime Employees: " + overtimeCount);
}
}
public class PayrollOOP {
public static void main(String[] args) {
// Objects model the entities: each employee holds its own data
List<Employee> employees = List.of(
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0));
int[] hours = {45, 38, 52, 40};
new PayrollSystem().runPayroll(employees, hours);
}
}#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// OOP style: the same payroll, modeled as collaborating objects
// A pay stub: one employee's pay for the week, as a small value object
struct PayStub {
std::string name;
double gross;
double tax;
double net;
};
// What every employee is and can do; each kind fills in how it is paid
class Employee {
public:
static constexpr double TAX_RATE = 0.20; // shared by every kind, written once
explicit Employee(std::string name) : name_(std::move(name)) {}
virtual ~Employee() = default;
const std::string& getName() const { return name_; }
// Polymorphism: each kind of employee works out its own gross pay
virtual double calculateGrossPay(int hours) const = 0;
// Each kind also says for itself whether a week's hours count as overtime
virtual bool hasOvertime(int hours) const = 0;
// Inheritance: the tax rule is shared by every kind
double calculateTax(double grossPay) const { return grossPay * TAX_RATE; }
// Abstraction: callers ask for a pay stub without knowing how it is worked out
PayStub generatePayStub(int hours) const {
double gross = calculateGrossPay(hours);
double tax = calculateTax(gross);
return {name_, gross, tax, gross - tax};
}
private:
std::string name_;
};
class HourlyEmployee : public Employee {
public:
static constexpr int OVERTIME_THRESHOLD = 40;
static constexpr double OVERTIME_MULTIPLIER = 1.5;
HourlyEmployee(std::string name, double hourlyRate)
: Employee(std::move(name)), hourlyRate_(checked(hourlyRate)) {}
double calculateGrossPay(int hours) const override {
if (hours < 0) {
throw std::invalid_argument("Hours cannot be negative");
}
if (hours > OVERTIME_THRESHOLD) {
double regular = OVERTIME_THRESHOLD * hourlyRate_;
double overtime =
(hours - OVERTIME_THRESHOLD) * hourlyRate_ * OVERTIME_MULTIPLIER;
return regular + overtime;
}
return hours * hourlyRate_;
}
bool hasOvertime(int hours) const override { return hours > OVERTIME_THRESHOLD; }
private:
// Encapsulation: the rate is checked once, here, and nothing outside can change it
static double checked(double rate) {
if (rate < 0) {
throw std::invalid_argument("Hourly rate cannot be negative");
}
return rate;
}
const double hourlyRate_;
};
class SalariedEmployee : public Employee {
public:
SalariedEmployee(std::string name, double annualSalary)
: Employee(std::move(name)), annualSalary_(checked(annualSalary)) {}
double calculateGrossPay(int) const override {
return annualSalary_ / 52; // the same every week, whatever the hours
}
bool hasOvertime(int) const override { return false; } // a salary has no overtime
private:
static double checked(double salary) {
if (salary < 0) {
throw std::invalid_argument("Salary cannot be negative");
}
return salary;
}
const double annualSalary_;
};
class PayrollSystem {
public:
void runPayroll(const std::vector<std::unique_ptr<Employee>>& employees,
const std::vector<int>& hoursList) const {
double totalGross = 0.0;
double totalTax = 0.0;
double totalNet = 0.0;
int overtimeCount = 0;
for (std::size_t i = 0; i < employees.size(); i++) {
const Employee& employee = *employees[i];
// The same calls for every employee; each object answers in its own way
PayStub stub = employee.generatePayStub(hoursList[i]);
totalGross += stub.gross;
totalTax += stub.tax;
totalNet += stub.net;
if (employee.hasOvertime(hoursList[i])) {
overtimeCount++;
}
std::printf("%s: Gross=$%.2f, Tax=$%.2f, Net=$%.2f\n",
stub.name.c_str(), stub.gross, stub.tax, stub.net);
}
std::printf("\nPayroll Summary:\n");
std::printf("Total Gross: $%.2f\n", totalGross);
std::printf("Total Tax: $%.2f\n", totalTax);
std::printf("Total Net: $%.2f\n", totalNet);
std::printf("Overtime Employees: %d\n", overtimeCount);
}
};
int main() {
// Objects model the entities: each employee holds its own data
std::vector<std::unique_ptr<Employee>> employees;
employees.push_back(std::make_unique<HourlyEmployee>("Alice", 35.0));
employees.push_back(std::make_unique<HourlyEmployee>("Bob", 42.0));
employees.push_back(std::make_unique<HourlyEmployee>("Charlie", 28.0));
employees.push_back(std::make_unique<SalariedEmployee>("Diana", 114400.0));
std::vector<int> hours = {45, 38, 52, 40};
PayrollSystem().runPayroll(employees, hours);
return 0;
}// OOP style: the same payroll, modeled as collaborating objects
// A pay stub: one employee's pay for the week, as a small value object
interface PayStub {
readonly name: string;
readonly gross: number;
readonly tax: number;
readonly net: number;
}
// What every employee is and can do; each kind fills in how it is paid
abstract class Employee {
static readonly TAX_RATE = 0.2; // shared by every kind, written once
constructor(private readonly name: string) {}
getName(): string {
return this.name;
}
// Polymorphism: each kind of employee works out its own gross pay
abstract calculateGrossPay(hours: number): number;
// Each kind also says for itself whether a week's hours count as overtime
abstract hasOvertime(hours: number): boolean;
// Inheritance: the tax rule is shared by every kind
calculateTax(grossPay: number): number {
return grossPay * Employee.TAX_RATE;
}
// Abstraction: callers ask for a pay stub without knowing how it is worked out
generatePayStub(hours: number): PayStub {
const gross = this.calculateGrossPay(hours);
const tax = this.calculateTax(gross);
return { name: this.name, gross, tax, net: gross - tax };
}
}
class HourlyEmployee extends Employee {
static readonly OVERTIME_THRESHOLD = 40;
static readonly OVERTIME_MULTIPLIER = 1.5;
// Encapsulation: the rate is checked once, here, and nothing outside can change it
private readonly hourlyRate: number;
constructor(name: string, hourlyRate: number) {
super(name);
if (hourlyRate < 0) {
throw new Error("Hourly rate cannot be negative");
}
this.hourlyRate = hourlyRate;
}
calculateGrossPay(hours: number): number {
if (hours < 0) {
throw new Error("Hours cannot be negative");
}
const threshold = HourlyEmployee.OVERTIME_THRESHOLD;
if (hours > threshold) {
const regular = threshold * this.hourlyRate;
const overtime =
(hours - threshold) * this.hourlyRate * HourlyEmployee.OVERTIME_MULTIPLIER;
return regular + overtime;
}
return hours * this.hourlyRate;
}
hasOvertime(hours: number): boolean {
return hours > HourlyEmployee.OVERTIME_THRESHOLD;
}
}
class SalariedEmployee extends Employee {
private readonly annualSalary: number;
constructor(name: string, annualSalary: number) {
super(name);
if (annualSalary < 0) {
throw new Error("Salary cannot be negative");
}
this.annualSalary = annualSalary;
}
calculateGrossPay(_hours: number): number {
return this.annualSalary / 52; // the same every week, whatever the hours
}
hasOvertime(_hours: number): boolean {
return false; // a salary has no overtime
}
}
class PayrollSystem {
runPayroll(employees: Employee[], hoursList: number[]): void {
let totalGross = 0.0;
let totalTax = 0.0;
let totalNet = 0.0;
let overtimeCount = 0;
employees.forEach((employee, i) => {
// The same calls for every employee; each object answers in its own way
const stub = employee.generatePayStub(hoursList[i]);
totalGross += stub.gross;
totalTax += stub.tax;
totalNet += stub.net;
if (employee.hasOvertime(hoursList[i])) {
overtimeCount++;
}
console.log(
`${stub.name}: Gross=$${stub.gross.toFixed(2)}, ` +
`Tax=$${stub.tax.toFixed(2)}, Net=$${stub.net.toFixed(2)}`
);
});
console.log("\nPayroll Summary:");
console.log(`Total Gross: $${totalGross.toFixed(2)}`);
console.log(`Total Tax: $${totalTax.toFixed(2)}`);
console.log(`Total Net: $${totalNet.toFixed(2)}`);
console.log(`Overtime Employees: ${overtimeCount}`);
}
}
// Objects model the entities: each employee holds its own data
const employees: Employee[] = [
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0),
];
const hours = [45, 38, 52, 40];
new PayrollSystem().runPayroll(employees, hours);using System;
using System.Collections.Generic;
using static System.FormattableString;
// OOP style: the same payroll, modeled as collaborating objects
// A pay stub: one employee's pay for the week, as a small value object
public record PayStub(string Name, double Gross, double Tax, double Net);
// What every employee is and can do; each kind fills in how it is paid
public abstract class Employee
{
public const double TaxRate = 0.20; // shared by every kind, written once
protected Employee(string name)
{
Name = name;
}
public string Name { get; }
// Polymorphism: each kind of employee works out its own gross pay
public abstract double CalculateGrossPay(int hours);
// Each kind also says for itself whether a week's hours count as overtime
public abstract bool HasOvertime(int hours);
// Inheritance: the tax rule is shared by every kind
public double CalculateTax(double grossPay)
{
return grossPay * TaxRate;
}
// Abstraction: callers ask for a pay stub without knowing how it is worked out
public PayStub GeneratePayStub(int hours)
{
double gross = CalculateGrossPay(hours);
double tax = CalculateTax(gross);
return new PayStub(Name, gross, tax, gross - tax);
}
}
public class HourlyEmployee : Employee
{
public const int OvertimeThreshold = 40;
public const double OvertimeMultiplier = 1.5;
// Encapsulation: the rate is checked once, here, and nothing outside can change it
private readonly double _hourlyRate;
public HourlyEmployee(string name, double hourlyRate) : base(name)
{
if (hourlyRate < 0)
{
throw new ArgumentException("Hourly rate cannot be negative");
}
_hourlyRate = hourlyRate;
}
public override double CalculateGrossPay(int hours)
{
if (hours < 0)
{
throw new ArgumentException("Hours cannot be negative");
}
if (hours > OvertimeThreshold)
{
double regular = OvertimeThreshold * _hourlyRate;
double overtime =
(hours - OvertimeThreshold) * _hourlyRate * OvertimeMultiplier;
return regular + overtime;
}
return hours * _hourlyRate;
}
public override bool HasOvertime(int hours)
{
return hours > OvertimeThreshold;
}
}
public class SalariedEmployee : Employee
{
private readonly double _annualSalary;
public SalariedEmployee(string name, double annualSalary) : base(name)
{
if (annualSalary < 0)
{
throw new ArgumentException("Salary cannot be negative");
}
_annualSalary = annualSalary;
}
public override double CalculateGrossPay(int hours)
{
return _annualSalary / 52; // the same every week, whatever the hours
}
public override bool HasOvertime(int hours)
{
return false; // a salary has no overtime
}
}
public class PayrollSystem
{
public void RunPayroll(List<Employee> employees, int[] hoursList)
{
double totalGross = 0.0;
double totalTax = 0.0;
double totalNet = 0.0;
int overtimeCount = 0;
for (int i = 0; i < employees.Count; i++)
{
Employee employee = employees[i];
// The same calls for every employee; each object answers in its own way
PayStub stub = employee.GeneratePayStub(hoursList[i]);
totalGross += stub.Gross;
totalTax += stub.Tax;
totalNet += stub.Net;
if (employee.HasOvertime(hoursList[i]))
{
overtimeCount++;
}
var (name, gross, tax, net) = stub;
Console.WriteLine(Invariant(
$"{name}: Gross=${gross:F2}, Tax=${tax:F2}, Net=${net:F2}"));
}
Console.WriteLine("\nPayroll Summary:");
Console.WriteLine(Invariant($"Total Gross: ${totalGross:F2}"));
Console.WriteLine(Invariant($"Total Tax: ${totalTax:F2}"));
Console.WriteLine(Invariant($"Total Net: ${totalNet:F2}"));
Console.WriteLine($"Overtime Employees: {overtimeCount}");
}
}
public static class PayrollOOP
{
public static void Main()
{
// Objects model the entities: each employee holds its own data
var employees = new List<Employee>
{
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0),
};
int[] hours = { 45, 38, 52, 40 };
new PayrollSystem().RunPayroll(employees, hours);
}
}package main
import (
"errors"
"fmt"
)
// OOP style: the same payroll, modeled as collaborating objects
// PayStub is one employee's pay for the week, as a small value
type PayStub struct {
Name string
Gross float64
Tax float64
Net float64
}
// TaxRate is shared by every kind of employee, written once
const TaxRate = 0.20
// Employee is what every employee can do; each kind fills in how it is paid.
// Go has no inheritance: an interface says what each kind must do, and the
// shared part (the name, the tax, the pay stub) is written once beside it.
type Employee interface {
Name() string
CalculateGrossPay(hours int) float64 // polymorphism: each kind its own way
HasOvertime(hours int) bool // each kind also says if its hours are overtime
}
// person holds what every kind of employee has; each kind embeds it
type person struct {
name string
}
func (p person) Name() string { return p.name }
// CalculateTax is the tax rule every kind shares
func CalculateTax(grossPay float64) float64 {
return grossPay * TaxRate
}
// GeneratePayStub: callers ask for a pay stub without knowing how it is worked out
func GeneratePayStub(e Employee, hours int) PayStub {
gross := e.CalculateGrossPay(hours)
tax := CalculateTax(gross)
return PayStub{Name: e.Name(), Gross: gross, Tax: tax, Net: gross - tax}
}
// HourlyEmployee is paid by the hour, with overtime past the threshold
type HourlyEmployee struct {
person
hourlyRate float64 // encapsulation: unexported, checked once in NewHourlyEmployee
}
const (
OvertimeThreshold = 40
OvertimeMultiplier = 1.5
)
func NewHourlyEmployee(name string, hourlyRate float64) (*HourlyEmployee, error) {
if hourlyRate < 0 {
return nil, errors.New("hourly rate cannot be negative")
}
return &HourlyEmployee{person: person{name}, hourlyRate: hourlyRate}, nil
}
func (h *HourlyEmployee) CalculateGrossPay(hours int) float64 {
if hours < 0 {
panic("hours cannot be negative") // Go has no exceptions: a bad argument panics
}
if hours > OvertimeThreshold {
regular := OvertimeThreshold * h.hourlyRate
overtime := float64(hours-OvertimeThreshold) * h.hourlyRate * OvertimeMultiplier
return regular + overtime
}
return float64(hours) * h.hourlyRate
}
func (h *HourlyEmployee) HasOvertime(hours int) bool {
return hours > OvertimeThreshold
}
// SalariedEmployee is paid the same every week
type SalariedEmployee struct {
person
annualSalary float64
}
func NewSalariedEmployee(name string, annualSalary float64) (*SalariedEmployee, error) {
if annualSalary < 0 {
return nil, errors.New("salary cannot be negative")
}
return &SalariedEmployee{person: person{name}, annualSalary: annualSalary}, nil
}
func (s *SalariedEmployee) CalculateGrossPay(hours int) float64 {
return s.annualSalary / 52 // the same every week, whatever the hours
}
func (s *SalariedEmployee) HasOvertime(hours int) bool {
return false // a salary has no overtime
}
// PayrollSystem runs the payroll for its employees
type PayrollSystem struct{}
func (PayrollSystem) RunPayroll(employees []Employee, hoursList []int) {
totalGross, totalTax, totalNet := 0.0, 0.0, 0.0
overtimeCount := 0
for i, employee := range employees {
// The same calls for every employee; each object answers in its own way
stub := GeneratePayStub(employee, hoursList[i])
totalGross += stub.Gross
totalTax += stub.Tax
totalNet += stub.Net
if employee.HasOvertime(hoursList[i]) {
overtimeCount++
}
fmt.Printf("%s: Gross=$%.2f, Tax=$%.2f, Net=$%.2f\n",
stub.Name, stub.Gross, stub.Tax, stub.Net)
}
fmt.Println("\nPayroll Summary:")
fmt.Printf("Total Gross: $%.2f\n", totalGross)
fmt.Printf("Total Tax: $%.2f\n", totalTax)
fmt.Printf("Total Net: $%.2f\n", totalNet)
fmt.Printf("Overtime Employees: %d\n", overtimeCount)
}
// must stops the program when a constructor refuses its values
func must[T any](value T, err error) T {
if err != nil {
panic(err)
}
return value
}
func main() {
// Objects model the entities: each employee holds its own data
employees := []Employee{
must(NewHourlyEmployee("Alice", 35.0)),
must(NewHourlyEmployee("Bob", 42.0)),
must(NewHourlyEmployee("Charlie", 28.0)),
must(NewSalariedEmployee("Diana", 114_400.0)),
}
hours := []int{45, 38, 52, 40}
PayrollSystem{}.RunPayroll(employees, hours)
}It prints:
Alice: Gross=$1662.50, Tax=$332.50, Net=$1330.00
Bob: Gross=$1596.00, Tax=$319.20, Net=$1276.80
Charlie: Gross=$1624.00, Tax=$324.80, Net=$1299.20
Diana: Gross=$2200.00, Tax=$440.00, Net=$1760.00
Payroll Summary:
Total Gross: $7082.50
Total Tax: $1416.50
Total Net: $5666.00
Overtime Employees: 2
These are the same ten lines as in Imperative Programming and Procedural Programming. The amounts did not change; the way the program is organised did.
Each employee is one object. The parallel lists are gone. An employee's name and rate live inside its object, so one employee's name can never be paired with another employee's rate, the slip that broke the payroll in Imperative Programming.
Each object checks its own data. HourlyEmployee("Alice", -50) stops with the error "Hourly rate cannot be negative", so a negative rate never gets into the payroll. The check is written once, in the class, and every new hourly employee passes through it. Compare Procedural Programming, where calculate_gross_pay worked out 500.00 for minus 10 hours at minus 50.00 an hour and nothing complained.
PayrollSystem never asks what kind of employee it has. run_payroll calls generate_pay_stub and has_overtime on every employee in the same way, and each object answers with its own class's rule. There is no if on the employee's type anywhere in it.
The code reads like the problem. Each employee produces its own pay stub, and the payroll system adds them up.
A New Kind of Employee
Now the company hires a contractor. In Procedural Programming, a new kind of employee meant opening calculate_gross_pay and adding another branch. Here it means writing one new class. A contractor is paid as in the procedural program, hours times rate with a 1.1 markup, and earns no overtime premium. Everything in the listing above stays exactly as it is, PayrollSystem included, and these lines are added:
# A new kind of employee is a new class; PayrollSystem is not changed
class ContractorEmployee(Employee):
MARKUP = 1.1 # a contractor's markup
def __init__(self, name: str, hourly_rate: float) -> None:
super().__init__(name)
if hourly_rate < 0:
raise ValueError("Hourly rate cannot be negative")
self._hourly_rate = hourly_rate
def calculate_gross_pay(self, hours: int) -> float:
if hours < 0:
raise ValueError("Hours cannot be negative")
return hours * self._hourly_rate * self.MARKUP
def has_overtime(self, hours: int) -> bool:
return False # a contractor is paid no overtime premium
# The same PayrollSystem, now with five employees
employees = [
HourlyEmployee("Alice", 35.0),
HourlyEmployee("Bob", 42.0),
HourlyEmployee("Charlie", 28.0),
SalariedEmployee("Diana", 114_400.0),
ContractorEmployee("Eve", 50.0),
]
hours = [45, 38, 52, 40, 45]
PayrollSystem().run_payroll(employees, hours)// A new kind of employee is a new class; PayrollSystem is not changed
class ContractorEmployee extends Employee {
static final double MARKUP = 1.1; // a contractor's markup
private final double hourlyRate;
public ContractorEmployee(String name, double hourlyRate) {
super(name);
if (hourlyRate < 0) {
throw new IllegalArgumentException("Hourly rate cannot be negative");
}
this.hourlyRate = hourlyRate;
}
@Override
public double calculateGrossPay(int hours) {
if (hours < 0) {
throw new IllegalArgumentException("Hours cannot be negative");
}
return hours * hourlyRate * MARKUP;
}
@Override
public boolean hasOvertime(int hours) {
return false; // a contractor is paid no overtime premium
}
}
public class PayrollOOP {
public static void main(String[] args) {
// The same PayrollSystem, now with five employees
List<Employee> employees = List.of(
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0),
new ContractorEmployee("Eve", 50.0));
int[] hours = {45, 38, 52, 40, 45};
new PayrollSystem().runPayroll(employees, hours);
}
}// A new kind of employee is a new class; PayrollSystem is not changed
class ContractorEmployee : public Employee {
public:
static constexpr double MARKUP = 1.1; // a contractor's markup
ContractorEmployee(std::string name, double hourlyRate)
: Employee(std::move(name)), hourlyRate_(checked(hourlyRate)) {}
double calculateGrossPay(int hours) const override {
if (hours < 0) {
throw std::invalid_argument("Hours cannot be negative");
}
return hours * hourlyRate_ * MARKUP;
}
// a contractor is paid no overtime premium
bool hasOvertime(int) const override { return false; }
private:
static double checked(double rate) {
if (rate < 0) {
throw std::invalid_argument("Hourly rate cannot be negative");
}
return rate;
}
const double hourlyRate_;
};
int main() {
// The same PayrollSystem, now with five employees
std::vector<std::unique_ptr<Employee>> employees;
employees.push_back(std::make_unique<HourlyEmployee>("Alice", 35.0));
employees.push_back(std::make_unique<HourlyEmployee>("Bob", 42.0));
employees.push_back(std::make_unique<HourlyEmployee>("Charlie", 28.0));
employees.push_back(std::make_unique<SalariedEmployee>("Diana", 114400.0));
employees.push_back(std::make_unique<ContractorEmployee>("Eve", 50.0));
std::vector<int> hours = {45, 38, 52, 40, 45};
PayrollSystem().runPayroll(employees, hours);
return 0;
}// A new kind of employee is a new class; PayrollSystem is not changed
class ContractorEmployee extends Employee {
static readonly MARKUP = 1.1; // a contractor's markup
private readonly hourlyRate: number;
constructor(name: string, hourlyRate: number) {
super(name);
if (hourlyRate < 0) {
throw new Error("Hourly rate cannot be negative");
}
this.hourlyRate = hourlyRate;
}
calculateGrossPay(hours: number): number {
if (hours < 0) {
throw new Error("Hours cannot be negative");
}
return hours * this.hourlyRate * ContractorEmployee.MARKUP;
}
hasOvertime(_hours: number): boolean {
return false; // a contractor is paid no overtime premium
}
}
// The same PayrollSystem, now with five employees
const employees: Employee[] = [
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0),
new ContractorEmployee("Eve", 50.0),
];
const hours = [45, 38, 52, 40, 45];
new PayrollSystem().runPayroll(employees, hours);// A new kind of employee is a new class; PayrollSystem is not changed
public class ContractorEmployee : Employee
{
public const double Markup = 1.1; // a contractor's markup
private readonly double _hourlyRate;
public ContractorEmployee(string name, double hourlyRate) : base(name)
{
if (hourlyRate < 0)
{
throw new ArgumentException("Hourly rate cannot be negative");
}
_hourlyRate = hourlyRate;
}
public override double CalculateGrossPay(int hours)
{
if (hours < 0)
{
throw new ArgumentException("Hours cannot be negative");
}
return hours * _hourlyRate * Markup;
}
public override bool HasOvertime(int hours)
{
return false; // a contractor is paid no overtime premium
}
}
public static class PayrollOOP
{
public static void Main()
{
// The same PayrollSystem, now with five employees
var employees = new List<Employee>
{
new HourlyEmployee("Alice", 35.0),
new HourlyEmployee("Bob", 42.0),
new HourlyEmployee("Charlie", 28.0),
new SalariedEmployee("Diana", 114_400.0),
new ContractorEmployee("Eve", 50.0),
};
int[] hours = { 45, 38, 52, 40, 45 };
new PayrollSystem().RunPayroll(employees, hours);
}
}// ContractorEmployee is a new kind of employee: a new type; PayrollSystem is unchanged
type ContractorEmployee struct {
person
hourlyRate float64
}
// Markup is a contractor's markup
const Markup = 1.1
func NewContractorEmployee(
name string, hourlyRate float64,
) (*ContractorEmployee, error) {
if hourlyRate < 0 {
return nil, errors.New("hourly rate cannot be negative")
}
return &ContractorEmployee{person: person{name}, hourlyRate: hourlyRate}, nil
}
func (c *ContractorEmployee) CalculateGrossPay(hours int) float64 {
if hours < 0 {
panic("hours cannot be negative")
}
return float64(hours) * c.hourlyRate * Markup
}
func (c *ContractorEmployee) HasOvertime(hours int) bool {
return false // a contractor is paid no overtime premium
}
func main() {
// The same PayrollSystem, now with five employees
employees := []Employee{
must(NewHourlyEmployee("Alice", 35.0)),
must(NewHourlyEmployee("Bob", 42.0)),
must(NewHourlyEmployee("Charlie", 28.0)),
must(NewSalariedEmployee("Diana", 114_400.0)),
must(NewContractorEmployee("Eve", 50.0)),
}
hours := []int{45, 38, 52, 40, 45}
PayrollSystem{}.RunPayroll(employees, hours)
}Run together with the classes above, it prints:
Alice: Gross=$1662.50, Tax=$332.50, Net=$1330.00
Bob: Gross=$1596.00, Tax=$319.20, Net=$1276.80
Charlie: Gross=$1624.00, Tax=$324.80, Net=$1299.20
Diana: Gross=$2200.00, Tax=$440.00, Net=$1760.00
Eve: Gross=$2475.00, Tax=$495.00, Net=$1980.00
Payroll Summary:
Total Gross: $9557.50
Total Tax: $1911.50
Total Net: $7646.00
Overtime Employees: 2
Eve worked the same 45 hours as Alice. Alice's class pays her overtime past 40 hours and counts her as an overtime employee; Eve's class adds the markup instead and answers no to has_overtime, so the count stays at 2. PayrollSystem did not change by a single line. Adding new behaviour without editing code that already works is the idea behind the open/closed principle, which O — Open/Closed Principle covers.
Watch the Objects Answer
Here is the same payroll, one step at a time. It starts where Procedural Programming ended: four lists and one function with a branch for each type. Press "Bundle into objects" and each employee's name and rate move into an object of their own, each type becomes a class, and the week's hours go to PayrollSystem. Then step through the payroll and watch where each method is found: generate_pay_stub and calculate_tax come from Employee, written once for every kind, while calculate_gross_pay and has_overtime come from each object's own class. "Hire a contractor" adds Eve, and PayrollSystem stays exactly as it was.

Imperative, Procedural and Object-Oriented Side by Side
Here is the same payroll problem in all three styles:
| Question | Imperative | Procedural | Object-oriented |
|---|---|---|---|
| Where does the data live? | In parallel lists and loose variables | In parallel lists, passed into functions | Inside one object for each employee |
| How is the code organised? | One long run of statements | Functions and the calls between them | Classes with their own methods |
| How do you add a salaried employee? | More if and else in the main loop | Another branch in calculate_gross_pay | A new SalariedEmployee class, nothing else changed |
| What protects the data? | Nothing: any line can change any variable | Nothing: functions accept any values | Each class checks its data when an object is made |
| What about ten kinds of employee? | A ten-way chain of if and elif | The same chain inside a function | Ten classes, each with its own calculate_gross_pay |
| What does the main program read like? | A recipe: step 1, step 2, step 3 | An outline: call A, then B, then C | A conversation: ask each employee for a pay stub |
Each style adds structure to the one before it. What objects add is that the behaviour belongs to the thing it describes: an employee knows how to work out its own pay.
What Objects Help With in Large Programs
Objects earn their keep as programs grow. Here is what they help with, and why.
The code follows the problem. Real systems are full of things that have data and behaviour, such as customers, orders and accounts. Objects let you write those things down directly, so the structure of the code matches the structure of the problem, and the code becomes easier to understand and to discuss.
Each rule lives in one place. An object guards its own state and offers only what callers need. A BankAccount object can refuse any withdrawal that would take its balance below zero, and then that rule lives in one class and no other code has to remember it. In a large program, keeping each rule in one place is what keeps it true.
New kinds can be added without editing what works. As the contractor showed, a new kind of object can join a program without any change to the code that uses it. This is the root of the open/closed principle and of most design patterns. The book that named the classic patterns, Design Patterns: Elements of Reusable Object-Oriented Software, says its catalog "contains 23 design patterns", all built from objects, and the Design Patterns - Low Level Design course covers every one of them.
Shared behaviour is written once. The tax rule lives in Employee and serves every kind of employee. Add twenty kinds and it is still written once.
People can work on different parts at the same time. Splitting a program into parts with agreed methods lets several people build those parts at once. This was one of the first arguments for splitting software into modules: in 1972 David Parnas listed among the expected benefits that "development time should be shortened because separate groups would work on each module with little need for communication". Classes, with their agreed methods, are one way to draw those boundaries.
Where Objects Get in the Way
Objects are not the right tool for every problem, and knowing where they get in the way makes you a better designer.
Small scripts. A 50-line script that renames some files does not need a FileRenamer class and a RenameStrategy interface. A plain function is clearer.
Deep inheritance. Inheritance ties a child class closely to its parent. The Gang of Four, the authors of the patterns book, explain the cost: "inheritance exposes a subclass to details of its parent's implementation", so a change in a parent can break its children, and the deeper the hierarchy, the more there is to break. Their advice is "Favor object composition over class inheritance." Composition vs Inheritance — Favor Composition shows how to follow it.
State that changes. Objects usually hold data that changes over time. When several threads share an object and change it without coordinating, the result can depend on which thread happens to run first, a bug called a race condition. Functional programming avoids much of this by using data that never changes after it is made.
Pure data transformations. When the job is to turn data in one form into another, step by step, a chain of plain functions is often clearer than wrapping each step in an object.
Over-engineering. Objects make it easy to build elaborate class hierarchies and layers of patterns where a simple function would do. KISS — Keep It Simple, Stupid and YAGNI — You Aren't Gonna Need It are the guard against this.
Common Misconceptions About OOP
"Using classes makes code object-oriented." Putting functions inside a class does not make code object-oriented. A class with only static methods and no data of its own is procedural code with a class name around it. Object-oriented design is about things that keep their own state, behave in their own way and have clear responsibilities.
"More classes make a better design." Good design avoids complexity it does not need. A MathUtils class whose only member is a static calculate_tax() method does exactly what a plain function would, so the class adds nothing. If a concept does not need to be an object, leave it as a function.
"Inheritance is the most important feature." Inheritance is the feature most often overused. Encapsulation and polymorphism do more of the work in a good design, and the Gang of Four's advice, quoted above, is to prefer composition.
"OOP replaces the other paradigms." In practice you mix them. The body of every Java method is imperative code. Python's documentation calls Python multi-paradigm: "you can write programs or libraries that are largely procedural, object-oriented, or functional", and it describes list comprehensions as "borrowed from the functional programming language Haskell".
Where This Course Goes from Here
That is the big picture. The rest of Foundations - Low Level Design takes each part in depth:
- Classes and Objects — Blueprint vs Instance starts the core pillars: classes, constructors, encapsulation, abstraction, inheritance, polymorphism and enums.
- Interfaces vs Abstract Classes starts the relationships between classes and objects: association, aggregation, composition, dependency, realization and generalization.
- Introduction to UML — Why Visual Modeling Matters starts the diagrams that draw these designs.
- Why Design Principles Exist — The Cost of Bad Design starts the design principles, SOLID first and then the ones beyond it, followed by domain modelling, clean code and refactoring, architecture, and the interview itself.
After this course, Design Patterns - Low Level Design covers the Gang of Four's patterns and more, and Design Problems - Low Level Design applies all of it to real systems such as a parking lot, an elevator, a chess game and a ride-sharing service.
Key Takeaways
- An object keeps its own data, its state, together with the methods that work on it, its behaviour, and every object has its own identity.
- Four ideas carry object-oriented design: encapsulation, abstraction, inheritance and polymorphism.
- Compared with procedural code, the behaviour belongs to the thing it describes: each employee works out its own pay, and
PayrollSystemasks every employee in the same way. - A new kind of object can join without changing the code that uses it, as the contractor did.
- Objects get in the way in small scripts, in pure data transformations and in deep inheritance.
Functional Programming vs OOP — When to Use What comes next, and finishes the tour of programming styles.