OOP Documentation
OOP on one page — the four pillars, Java vs C++ vs Python, abstract class vs interface, SOLID and common design patterns.
Object-oriented programming on one page: the four pillars, the differences interviewers ask about, how Java, C++ and Python each do it, SOLID and the common design patterns. For revision questions see Top 50 OOP interview questions.
1. Core Ideas
| Term | Meaning |
|---|---|
| Class | Blueprint for objects |
| Object | An instance with its own data |
| Field / attribute | Data in an object |
| Method | Behaviour of an object |
| Constructor | Sets up a new object |
| Interface | A contract of methods |
| Abstract class | Partly built class that can't be created directly |
2. The Four Pillars
| Pillar | One line | Achieved with |
|---|---|---|
| Encapsulation | Hide data, expose safe methods | private fields, getters and setters |
| Abstraction | Show what, hide how | Interfaces, abstract classes |
| Inheritance | Reuse and extend a class (IS-A) | extends, : |
| Polymorphism | One call, many behaviours | Overloading, overriding |
Worked explanations: Four Pillars of OOP.
3. One Class in Three Languages
Java
class Animal {
private final String name;
Animal(String name) { this.name = name; }
String getName() { return name; }
String sound() { return "..."; }
}
class Dog extends Animal {
Dog(String name) { super(name); }
@Override String sound() { return "Woof"; }
}
C++
class Animal {
string name;
public:
Animal(string n) : name(n) {}
virtual ~Animal() = default;
virtual string sound() const { return "..."; }
};
class Dog : public Animal {
public:
using Animal::Animal;
string sound() const override { return "Woof"; }
};
Python
class Animal:
def __init__(self, name):
self._name = name
def sound(self):
return "..."
class Dog(Animal):
def sound(self):
return "Woof"
4. Language Differences
| Feature | Java | C++ | Python |
|---|---|---|---|
| Multiple inheritance | Interfaces only | Yes | Yes (MRO) |
| Runtime dispatch | Default | Needs virtual |
Default |
| Access control | private, default, protected, public |
private, protected, public |
Convention (_x, __x) |
| Memory | Garbage collected | Manual / RAII | Garbage collected |
| Interfaces | interface |
Pure virtual classes | abc, Protocol, duck typing |
| Destructor | None (close()) |
~Class() |
__del__ (avoid) |
| Operator overloading | No | Yes | Yes (__add__) |
5. Polymorphism
| Overloading | Overriding | |
|---|---|---|
| Also called | Compile-time | Runtime |
| Where | Same class | Parent and child |
| Signature | Different parameters | Same |
| Return type alone | Not enough | Same or a subtype |
Animal a = new Dog("Tommy");
a.sound(); // "Woof": decided at runtime by the real object
static, private and final methods can't be overridden.
6. Abstract Class vs Interface
| Abstract class | Interface | |
|---|---|---|
| State | Yes | Constants only |
| Constructor | Yes | No |
| Methods | Abstract + concrete | Abstract, default, static |
| A class can use | One | Many |
| Relationship | IS-A | CAN-DO |
Details: Abstract Class vs Interface.
7. Relationships
| Relationship | Meaning | Example |
|---|---|---|
| Inheritance | IS-A | Dog is an Animal |
| Association | Uses | Teacher and Student |
| Aggregation | HAS-A, parts live alone | Department has Students |
| Composition | HAS-A, parts die with the whole | House has Rooms |
Prefer composition over inheritance unless it's a true IS-A: it's more flexible and less fragile.
Aim for low coupling (classes depend little on each other) and high cohesion (each class does one job).
8. Constructors and Keywords
| Keyword | Meaning |
|---|---|
this |
The current object |
super |
The parent class |
static |
Belongs to the class, not objects |
final |
Variable: can't reassign. Method: can't override. Class: can't extend |
abstract |
Must be completed by a subclass |
Constructor kinds: default, parameterised, copy, private (Singleton). this(...) and super(...) must come first. See Classes, Objects and Constructors.
9. SOLID
| Letter | Principle | Means |
|---|---|---|
| S | Single responsibility | One reason to change |
| O | Open/closed | Extend without editing old code |
| L | Liskov substitution | Subclasses work wherever the parent does |
| I | Interface segregation | Small, focused interfaces |
| D | Dependency inversion | Depend on abstractions, inject them |
Examples with fixes: SOLID Principles.
10. Creational Patterns
Singleton — one shared instance:
class Config {
private static final Config INSTANCE = new Config();
private Config() {}
static Config get() { return INSTANCE; }
}
Factory — create objects without naming the class:
static Shape create(String type) {
return switch (type) {
case "circle" -> new Circle();
case "square" -> new Square();
default -> throw new IllegalArgumentException(type);
};
}
Builder — build complex objects step by step: new User.Builder().name("Asha").age(21).build().
11. Structural and Behavioural Patterns
| Pattern | Use | Example |
|---|---|---|
| Adapter | Make an incompatible class fit | Wrap an old payment API |
| Decorator | Add behaviour by wrapping | Add logging to a service |
| Facade | One simple front for many parts | ParkingLot.park() |
| Proxy | Control access to an object | Lazy loading, caching |
| Strategy | Swap algorithms at runtime | Discount or payment rules |
| Observer | Notify subscribers of changes | Event listeners |
| Template method | Fixed steps, variable details | Report generation |
| Command | Wrap an action as an object | Undo / redo |
Strategy example:
interface Discount { double apply(double price); }
class Checkout {
private final Discount discount;
Checkout(Discount d) { discount = d; }
double total(double price) { return discount.apply(price); }
}
new Checkout(p -> p * 0.8).total(500); // 400.0
12. Practice Problems
- Model a bank account with
depositandwithdraw, and block invalid amounts. - Build
Shapeclasses witharea()and print them through a list ofShape. - Add payment methods using the Strategy pattern.
- Design a library system's classes on paper.
- Design a parking lot and name the patterns you used.
13. Interview Questions
Encapsulation vs abstraction? Encapsulation hides data; abstraction hides complexity.
Why no multiple class inheritance in Java? To avoid the diamond problem.
Can a constructor be private? Yes, for Singleton and utility classes.
What does virtual do in C++? It lets the call use the real object's method at runtime.
Why a virtual destructor? So deleting through a base pointer also runs the child's destructor.
Shallow vs deep copy? Shallow shares nested objects; deep copies them too.
Composition vs inheritance? HAS-A vs IS-A; composition is more flexible.
What is the Liskov principle? A subclass must work anywhere its parent is expected.
14. Cheat Sheet & References
Pillars
Encapsulation: hide data
Abstraction: hide complexity
Inheritance: IS-A, reuse
Polymorphism: overload (compile time), override (runtime)
Comparisons
Abstract class: state, 1 parent, IS-A
Interface: contract, many, CAN-DO
Aggregation: part lives alone · Composition: part dies with the whole
Patterns
Singleton: one instance · Factory: hide creation · Builder: step by step
Strategy: swap algorithm · Observer: notify subscribers
Adapter: fit an interface · Decorator: wrap to add behaviour · Facade: simple front
SOLID
S one job · O extend, don't edit · L subclasses substitute
I small interfaces · D depend on abstractions