Object-oriented programming organizes code around objects: bundles of data plus the methods that are allowed to work on that data. Four ideas, usually called the four pillars, explain why that is useful: encapsulation (an object guards its own state), abstraction (callers depend on what an object does, not how), inheritance (a class reuses and extends another) and polymorphism (one call, different behavior depending on the object). Every design pattern in this track is built from these four, so it pays to see each one clearly, and to know how each is misused.
Think of it like
A bank branch
You never open the vault and change your balance yourself: you ask a teller, who checks the rules first (encapsulation). You do not need to know how the bank's ledger works to say "withdraw 50" (abstraction). A savings account and a checking account share the same deposit and withdrawal procedure, written once (inheritance). And at the end of the month the branch runs one procedure, "close the month", on every account, yet savings accounts earn interest while checking accounts pay a fee (polymorphism).
Why objects
Start without objects. A small bank keeps each account as a plain record (a kind tag and a balance) and runs its month-end rules in one function that switches on kind. This is the Before version in the visualizer above.
type AccountData = { kind: string; balance: number };
function closeMonth(accounts: AccountData[]): string[] {
const report: string[] = [];
for (const a of accounts) {
switch (a.kind) {
case "savings": {
const interest = a.balance * 0.01;
a.balance += interest;
report.push(`+${interest} interest`);
break;
}
case "checking":
a.balance -= 5;
report.push("-5 fee");
break;
}
}
return report;
}
const chk: AccountData = { kind: "checking", balance: 200 };
chk.balance -= 500; // nothing stops this: the balance is now -300- Nothing guards the data. Any line anywhere can write
balance. The rule "never below zero" must be re-checked by every piece of code that touches it, and one forgotten check breaks it. - The rules live away from the data. What a savings account does at month end is in
closeMonth(); what it does on withdrawal is in some other function. To understand one kind of account you read the whole program. - Every new kind edits every switch. A student account needs a new
caseincloseMonth()and in every otherswitchonkind, and missing one is a silent bug (the default does nothing). - Callers know every kind. Code that processes accounts must know all the
kindstrings, so a change to one kind ripples into code that has nothing to do with it.
Encapsulation
Encapsulation puts data and the code that changes it in one unit, and hides the data behind that code. The fields are private; the only way to change them is to call a method, and the method enforces the object's invariants (the rules that must always hold, such as "balance is never negative").
abstract class Account {
constructor(private balance: number) {
if (balance < 0) throw new Error("Negative balance");
}
getBalance(): number {
return this.balance;
}
deposit(amt: number): void {
if (amt <= 0) throw new Error("Bad amount");
this.balance += amt;
}
withdraw(amt: number): void {
if (amt > this.balance) throw new Error("Insufficient funds");
this.balance -= amt;
}
abstract monthEnd(): string;
}
// chk.balance -= 500; // compile error: 'balance' is privateWhat it buys you: the rule is written once, in the only code that can change the field, so it cannot be bypassed. The representation can change too (store cents instead of dollars, add an audit log) without touching any caller, because no caller ever saw the field.
Abstraction
Abstraction means working with an object through what it does while ignoring how it does it. In code that usually means depending on an abstract type (an interface or an abstract class) instead of a concrete class. Encapsulation hides the data inside one object; abstraction hides which kind of object you even have.
class Bank {
constructor(private accounts: Account[]) {}
closeMonth(): string[] {
const report: string[] = [];
for (const a of this.accounts) {
report.push(a.monthEnd()); // no switch, no kind
}
return report;
}
}What it buys you: Bank compiles and works without importing a single concrete account class. You can add kinds of account, or test Bank with a fake account, and its code does not change. This is the idea behind "program to an interface, not an implementation", covered in depth in Interfaces & Abstract Classes.
Inheritance
Inheritance lets a class (the subclass or child) start from another class (the superclass or parent): it gets the parent's fields and methods and adds or overrides only what differs. It also makes the child a subtype: a SavingsAccount can be used anywhere an Account is expected.
class SavingsAccount extends Account {
private rate = 0.01;
monthEnd(): string {
const interest = this.getBalance() * this.rate;
this.deposit(interest); // inherited from Account
return `+${interest} interest`;
}
}
class CheckingAccount extends Account {
private fee = 5;
monthEnd(): string {
this.withdraw(this.fee); // inherited, guard included
return `-${this.fee} fee`;
}
}What it buys you: deposit and withdraw, with their guards, are written once and every kind of account gets them. Note that CheckingAccount cannot write this.balance directly either: balance is private to Account, so even subclasses go through the guarded methods. A protected field would let them in, at the cost of a weaker guarantee.
Polymorphism
Polymorphism ("many forms") means one piece of code works with objects of different types, and each object responds in its own way. In Bank.closeMonth() the line a.monthEnd() is the same for every account, but which method runs is decided at runtime by the object's actual class. This is called dynamic dispatch, and it is what replaces the procedural switch.
| Kind | What varies | Example |
|---|---|---|
| Subtype (runtime) polymorphism | The method that runs, chosen by the object's class at runtime | a.monthEnd() runs SavingsAccount.monthEnd or CheckingAccount.monthEnd |
| Ad hoc polymorphism (overloading) | The function chosen by the argument types, at compile time | Java's print(int) and print(String); C++ operator overloading |
| Parametric polymorphism (generics) | Nothing: one implementation works for any type | Array<T>, List<T>, std::vector<T> |
What it buys you: the code that uses objects stops growing when new kinds appear. Adding StudentAccount means writing one class with its own monthEnd(); the loop in Bank handles it without a change. That is the open/closed principle (open for extension, closed for modification), and most behavioral patterns, starting with Strategy, are polymorphism put to work.
What the visualizer shows
The visualizer at the top of the page really runs the classes in its code panel and draws what happened. Press Play, or step with the arrow buttons; the running line is highlighted in the code and the caption names the pillar at each key step.
- Class diagram:
Bankholds a0..*aggregation to the abstractAccount;SavingsAccountandCheckingAccountinherit from it. Amber marks the code running now, sky blue the waiting caller, green something just created or returned, and violet the abstract type that declares the method being called. - Objects at runtime:
sav : SavingsAccountshowsbalance(inherited fromAccount) and its ownrate;chk : CheckingAccountshowsbalanceandfee.bankholdsaccounts = [sav, chk]. - Sequence of calls: one lifeline per object. A call to an inherited method on
savis a self-call onsav's own lifeline: the object is aSavingsAccount, the code that runs isAccount's. - Before / With OOP and Add student: the toggle switches to the procedural version, and Add student applies the change request to whichever version is shown, with badges on changed classes and a Change request panel that counts what each version had to change. On a phone the three views sit behind a Classes / Objects / Sequence switch.
- 1
Inheritance at creation
The client creates
savandchk. Each constructor setsbalance(declared inAccount) and the subclass's own field:rate = 0.01,fee = 5. - 2
Encapsulation: a valid change
chk.withdraw(50)runsAccount's code on aCheckingAccount(the caption says it is inherited), andchk.balancegoes from 200 to 150. - 3
Encapsulation: a refused change
chk.withdraw(500)reaches the guard: 500 is more than 150, so it throwsInsufficient fundsandbalancestays 150. The client catches the error, and a later step highlights the commented-outchk.balance -= 500, which would not compile. - 4
Abstraction
The client calls
bank.closeMonth().Bankonly knowsAccount; watch the aggregation toAccountlight up as it loops overaccounts. - 5
Polymorphism, first turn
bankcallsmonthEnd()onsav.Account.monthEndturns violet (declared there) andSavingsAccount.monthEndamber (it runs). It reads the balance and calls its inheriteddeposit(10):sav.balancebecomes 1010 and the call returns"+10 interest". - 6
Polymorphism, second turn
The same line calls
monthEnd()onchk; this timeCheckingAccount.monthEndruns, withdraws the fee (150 to 145) and returns"-5 fee".closeMonth()returns["+10 interest", "-5 fee"]. - 7
Before: the same run, procedurally
The client writes
chk.balancedirectly, twice, and nothing stops the overdraft: it reaches -350.closeMonth()takes the"savings"case and then the"checking"case, andchk.balanceends at -355.
How the pillars work together
| Pillar | The question it answers | In the visualizer |
|---|---|---|
| Encapsulation | Who may change this data, and under which rules? | Only deposit and withdraw change balance; withdraw(500) is refused |
| Abstraction | What does the caller need to know? | Bank holds Account[] and never mentions a concrete class |
| Inheritance | Where does shared behavior live? | deposit, withdraw, getBalance written once in Account, run on sav and chk |
| Polymorphism | Who decides which code runs? | The object: one a.monthEnd() line gives +10 interest and -5 fee |
They depend on each other. Polymorphism needs an abstraction to call through (Account.monthEnd()), the abstraction needs implementations, which inheritance (or implementing an interface) provides, and none of it is safe unless each object protects its own state. The change request shows the payoff:
| Add student accounts | Procedural | With OOP |
|---|---|---|
| Existing classes edited | 1 (Bank) | 0 |
| New classes | 0 | 1 (StudentAccount) |
| Lines changed in existing classes | 3 (+3 −0) | 0 |
| Classes touched | 1 | 1 |
Both versions touch one class, and the procedural edit is only three lines. The difference is which class. Procedurally, the new rule goes into Bank, the code every account passes through, and a real program would have more switch statements on kind to find and edit. With OOP, the new rule is a new class next to the others, and Bank, Account and the existing subclasses are not reopened.
OOP in different languages
| Feature | TypeScript | Java | Python | C++ |
|---|---|---|---|---|
| Access control | public, protected, private (checked at compile time only); #field is private at runtime too | public, protected, package-private (no keyword), private | Not enforced: _name means internal by convention, __name is name-mangled | public, protected, private, plus friend; members of a class default to private |
| Interfaces vs abstract classes | interface (compile time only, erased) and abstract class | interface (with default methods since Java 8) and abstract class | abc.ABC with @abstractmethod; typing.Protocol for structural interfaces | No interface keyword: a class with pure virtual functions (= 0) is abstract |
| Multiple inheritance | One superclass; any number of interfaces | One superclass; any number of interfaces | Yes, resolved by the method resolution order (C3 linearization) | Yes; virtual inheritance avoids duplicate bases in a diamond |
| Overridable methods | All methods | All except static, private and final ones | All methods | Only methods declared virtual; mark overrides with override |
| Duck typing | Structural typing: any object with the right shape fits a type, checked at compile time | No: types are nominal, a class must declare what it implements | Idiomatic: if it has the method, you can call it | At compile time through templates; C++20 concepts constrain them |
Common misconceptions
- "OOP means inheritance." Inheritance is the least essential pillar. Go has no classes or inheritance at all, yet has encapsulation (unexported names), abstraction and polymorphism through implicitly satisfied interfaces. Many modern designs prefer composition.
- "Encapsulation means private fields with getters and setters." Private fields are the mechanism; the point is that the object enforces its own rules. A setter that accepts anything encapsulates nothing.
- "Abstraction and encapsulation are the same thing." They work together but answer different questions: encapsulation protects an object's state from outside code, abstraction lets outside code ignore which object, and which implementation, it is talking to.
- "Polymorphism requires inheritance." Interfaces, duck typing in Python and generics are all polymorphism without a shared base class.
- "An abstract class and an interface are interchangeable." An abstract class can hold state and shared code but takes the single superclass slot (in Java and TypeScript); an interface is a pure contract a class can add freely. See Interfaces & Abstract Classes.
- "The four pillars are the definition of OOP." They are a teaching summary. Alan Kay, who coined the term, has said the big idea was messaging between objects, not classes.
Implementation
The scenario as a complete program, with the change request applied: an abstract Account that guards its private balance, three subclasses that each define monthEnd, and a Bank that loops over Account references. Amounts are whole numbers (think cents), so no floating-point rounding creeps in. The demo withdraws 50, has an overdraft refused, then closes the month polymorphically.
from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, opening_balance: int) -> None:
if opening_balance < 0:
raise ValueError("Opening balance cannot be negative")
self._balance = opening_balance # internal by convention
def get_balance(self) -> int:
return self._balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount: int) -> None:
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
@abstractmethod
def month_end(self) -> str:
...
class SavingsAccount(Account):
RATE_PERCENT = 1
def month_end(self) -> str:
interest = self.get_balance() * self.RATE_PERCENT // 100
if interest > 0:
self.deposit(interest)
return f"+{interest} interest"
class CheckingAccount(Account):
FEE = 5
def month_end(self) -> str:
self.withdraw(self.FEE)
return f"-{self.FEE} fee"
# The change request: one new class, nothing else edited.
class StudentAccount(Account):
def month_end(self) -> str:
return "no fee"
class Bank:
def __init__(self, accounts: list[Account]) -> None:
self._accounts = list(accounts)
def close_month(self) -> list[str]:
return [a.month_end() for a in self._accounts]
if __name__ == "__main__":
sav = SavingsAccount(1000)
chk = CheckingAccount(200)
stu = StudentAccount(300)
bank = Bank([sav, chk, stu])
chk.withdraw(50)
try:
chk.withdraw(500)
except ValueError as e:
print(e)
# chk._balance -= 500 would run: Python trusts you, and the
# underscore is the only warning. Account(100) raises TypeError,
# because Account has an abstract method.
print(bank.close_month())
print(sav.get_balance(), chk.get_balance(), stu.get_balance())
# Output:
# Insufficient funds
# ['+10 interest', '-5 fee', 'no fee']
# 1010 145 300Key takeaways
- Encapsulation keeps data private and changes it only through methods that enforce the object's rules. In the visualizer,
withdraw(500)is refused andchk.balancestays 150; procedurally it reaches -355. - Abstraction lets code depend on what an object does, not which class it is:
Bankworks withAccountand never names a concrete account class. - Inheritance shares behavior written once in a parent:
depositandwithdrawrun onsavandchkalthough onlyAccountdeclares them. Use it only for true is-a relationships. - Polymorphism lets one call run different code depending on the object: the same
a.monthEnd()returns+10 interestfor savings and-5 feefor checking. It replacesswitchstatements on a type tag. - Together they make change local: a student account is one new class with OOP (0 existing classes edited), versus a new
caseinBank(and in every otherswitchonkind) procedurally.
Common pitfalls
- Writing a public getter and setter for every private field: the object can no longer enforce its invariants, so it is encapsulated in name only.
- Using inheritance just to reuse code: the child inherits operations that break its own rules (Java's
Stack extends Vector) and becomes coupled to the parent's internals. Prefer composition. - Checking types with
instanceofor akindfield in code that already has an abstraction: the switch is back, and every new subclass must be added to it. - Overriding a method to throw or do nothing because the subclass cannot honor the parent's contract: callers of the parent type get surprised at runtime (a Liskov violation).
- Building deep or speculative hierarchies and interfaces before there is any variation to abstract over: more indirection, no benefit.
Interview tips
- Explain all four pillars with one running example (accounts, shapes, notifications) rather than four textbook definitions, and say what each one buys you.
- Be ready to separate abstraction from encapsulation, and to name a misuse of each pillar: setters for everything, leaky abstractions, inheriting for reuse,
instanceofchains. - Connect the pillars to design: "favor composition over inheritance", the open/closed principle and Liskov substitution all come from how these four are used, and most patterns are polymorphism plus composition.
Real-world applications
- Domain models: accounts, orders and shipments that protect their own invariants (a balance never negative, an order that cannot ship before it is paid).
- Plugin and driver architectures: code written against an abstract type (a database driver, a payment provider, a file system) and implementations chosen at runtime.
- UI toolkits: widgets that share layout and event handling through a base class and draw themselves polymorphically.
- Collections libraries:
List,Mapand iterator interfaces with many implementations behind one API. - Game engines and simulations: entities updated in one loop, each with its own
update()behavior.
Test yourself
In the visualizer, chk has a balance of 150 and the client calls chk.withdraw(500). What happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.