Object-Oriented Programming
Organising code around objects that bundle data with behaviour: classes, encapsulation, abstraction, inheritance, polymorphism and interfaces.
What is it?
Object-oriented programming (OOP) organises code around objects: bundles of data (fields) and the functions that operate on that data (methods). A class is a blueprint; each object created from it is an instance with its own data.
Four ideas are usually listed as the pillars of OOP:
- Encapsulation: keep an object's data private and expose only methods that keep it valid. A BankAccount lets you deposit and withdraw, not set balance to any number you like. - Abstraction: expose what an object does and hide how. You call file.read() without knowing about disk sectors. - Inheritance: a class can extend another, reusing and specialising its behaviour (SavingsAccount extends BankAccount). - Polymorphism: code written against a general type works with any specific type. Calling shape.area() runs the right version for a circle or a square, chosen at run time (dynamic dispatch).
An interface describes a set of methods without implementing them. Any class that provides those methods can be used wherever the interface is expected.
Explain like I'm 10
A class is a cookie cutter and objects are the cookies. Encapsulation is a vending machine: you press buttons, you don't reach inside. Polymorphism is a universal remote's 'power' button: one button, but each device turns itself on its own way.
Examples
Encapsulation: a class that protects its invariants (Python)
class BankAccount:
def __init__(self, owner: str):
self.owner = owner
self._balance = 0 # leading underscore: internal by convention
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 > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
@property
def balance(self) -> int: # read-only from outside
return self._balance
account = BankAccount("Ana")
account.deposit(100)
account.withdraw(30)
print(account.balance) # 70Polymorphism through an interface (TypeScript)
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area() { return Math.PI * this.radius ** 2; }
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
area() { return this.width * this.height; }
}
function totalArea(shapes: Shape[]): number {
// Doesn't know or care which concrete class each shape is
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
}
totalArea([new Circle(1), new Rectangle(2, 3)]); // ~9.14totalArea depends only on the Shape interface. Adding a Triangle later requires no change to it: the right area() is chosen at run time for each object.
Inheritance and overriding (Java)
abstract class Animal {
abstract String sound();
String describe() { return getClass().getSimpleName() + " says " + sound(); }
}
class Dog extends Animal {
@Override String sound() { return "woof"; }
}
class Cat extends Animal {
@Override String sound() { return "meow"; }
}
Animal pet = new Cat();
System.out.println(pet.describe()); // "Cat says meow"How it works
An object is, roughly, a block of data plus a pointer to its class. When you call obj.method(), the runtime looks the method up starting at the object's actual class, not the declared type of the variable. In compiled languages like C++ and Java this is often a vtable: a table of function pointers per class, so the call is one indirect jump. In Python and JavaScript, the lookup walks the class hierarchy (Python's method resolution order) or the prototype chain at run time.
That lookup is dynamic dispatch, and it's what makes polymorphism work: the same call site runs different code depending on the object.
Encapsulation is enforced differently per language: private in Java and C# is checked by the compiler; TypeScript's private only at compile time (#field is truly private at run time); Python relies on the _name convention.
Dynamic dispatch: pet.describe() where pet is a Cat
variable pet (declared Animal) --> [Cat object]
|
v
Cat vtable
sound() -> Cat.sound "meow"
describe() -> Animal.describe (inherited)Why does it exist?
As programs grow, data and the code that changes it get scattered, and any part can break any other part's assumptions. OOP groups them, puts rules next to the data they protect, and lets you swap implementations behind a stable interface. It also maps naturally onto many domains (users, orders, documents, UI widgets) and onto GUI and simulation software where it first became popular.
When to use it
Use classes when you have state with rules that must always hold (invariants), several implementations of the same behaviour (payment providers, storage backends, shapes), or long-lived entities with identity. Use interfaces at module boundaries so callers depend on behaviour rather than concrete classes.
When not to use it
Don't wrap everything in a class. Stateless logic is often clearer as a plain function, and plain data is often clearer as a record, dict or struct. Avoid deep inheritance hierarchies; they become rigid and fragile. Avoid classes that are only getters and setters around public data: that adds ceremony without encapsulating anything.
Common mistakes
Using inheritance just to reuse code when the subclass isn't truly a kind of the parent; composition is usually better.
Exposing all fields with public setters, which defeats encapsulation because any code can put the object in an invalid state.
Creating 'god objects' that know and do everything, instead of small classes with one clear responsibility.
Confusing a class with an instance, for example storing per-instance data in a class-level attribute that all instances then share.
Checking types with
if isinstance(...)/instanceofchains instead of letting polymorphism pick the behaviour.
Practice exercises
- Easy:
Write a
Rectangleclass with width and height, a method for area and perimeter, and a constructor that rejects non-positive sizes. - Medium:
Define a
Notifierinterface withsend(message), and implementEmailNotifierandSmsNotifier. Write a function that sends a message through a list of notifiers without knowing their concrete types. - Hard:
Model a library system (books, members, loans) with classes that enforce rules: a member can borrow at most 3 books, a book can't be lent twice. Write tests that try to break each rule.
Interview questions
What are the four pillars of OOP?
Encapsulation (hiding internal state behind methods), abstraction (exposing what an object does, not how), inheritance (deriving a class from another to reuse and specialise behaviour), and polymorphism (one interface, many implementations chosen at run time).
What is the difference between a class and an object?
A class is a definition or blueprint describing fields and methods. An object is a concrete instance of a class, with its own copy of the instance data.
What is encapsulation and why does it matter?
Bundling data with the methods that operate on it and restricting direct access to the data. It lets the class enforce invariants and change its internals without breaking callers.
What is the difference between abstraction and encapsulation?
Abstraction is about design: presenting a simple interface that hides complexity. Encapsulation is the mechanism: restricting access to internal state. Encapsulation is one way to achieve abstraction.
What is dynamic dispatch?
Choosing which method implementation to run based on the object's actual run-time class rather than the variable's declared type. It's how overridden methods get called through a base-class reference.
What is the difference between overriding and overloading?
Overriding is a subclass providing its own implementation of an inherited method, resolved at run time. Overloading is several methods with the same name but different parameter lists, resolved at compile time (Java, C#). Python and JavaScript don't support overloading directly.
What is the difference between an interface and an abstract class?
An interface declares methods a class must provide, usually without state, and a class can implement many. An abstract class can include fields and implemented methods, but a class can typically extend only one.
How does Python enforce private attributes?
It doesn't strictly. A single underscore (_x) is a convention meaning 'internal'. A double underscore (__x) triggers name mangling to _ClassName__x, which avoids accidental clashes in subclasses but is still accessible.
How do objects work in JavaScript without classes?
Through prototypes. Every object has a link to a prototype object, and property lookups that miss on the object continue up the prototype chain. The class syntax is sugar over this mechanism.
What is a common criticism of OOP?
Overuse leads to deep inheritance hierarchies, scattered mutable state and excess ceremony for simple problems. Many modern codebases mix OOP with functional techniques and prefer composition over inheritance.