Notes › OOP
Four Pillars of OOP
Object-Oriented Programming models a program as objects — bundles of data (fields) and behaviour (methods). Its four pillars:
| Pillar | One line |
|---|---|
| Encapsulation | bundle data + methods and hide the internal state |
| Abstraction | show what an object does, hide how |
| Inheritance | a class reuses and extends another class (IS-A) |
| Polymorphism | one interface, many forms — the same call behaves differently |
1. Encapsulation
Keep fields private; allow changes only through methods that enforce the rules.
public class BankAccount {
private double balance; // hidden — no one can set it to -1000
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("Amount must be positive");
balance += amt;
}
public void withdraw(double amt) {
if (amt > balance) throw new IllegalStateException("Insufficient balance");
balance -= amt;
}
public double getBalance() { return balance; } // read-only access
}
Benefits: data stays valid, internal changes don't break other code, easier debugging.
- Data hiding is part of encapsulation (using access modifiers).
- Python has no true
private;_xis a convention and__xtriggers name mangling.
2. Abstraction
Expose a simple interface and hide complexity. You press a car's accelerator without knowing fuel injection.
interface Payment {
void pay(double amount); // WHAT — every payment can pay
}
class UpiPayment implements Payment {
public void pay(double amount) { // HOW — hidden inside
System.out.println("Paid ₹" + amount + " via UPI");
}
}
Achieved with abstract classes and interfaces (see Abstract Class vs Interface).
Encapsulation vs abstraction
| Encapsulation | Abstraction | |
|---|---|---|
| Focus | hiding data / protecting state | hiding complexity / implementation |
| Level | implementation level | design level |
| Tool | access modifiers, getters/setters | abstract classes, interfaces |
| Question it answers | "how do I protect this?" | "what should the user see?" |
3. Inheritance
A child (subclass) gets the fields and methods of a parent (superclass) and can add or override them. It models an IS-A relationship: a Dog IS-A Animal.
class Animal {
protected String name;
Animal(String name) { this.name = name; }
void eat() { System.out.println(name + " eats"); }
void sound() { System.out.println("..."); }
}
class Dog extends Animal {
Dog(String name) { super(name); } // call the parent constructor
@Override void sound() { System.out.println(name + " barks"); }
void fetch() { System.out.println(name + " fetches"); }
}
Types of inheritance
| Type | Shape | Java classes? |
|---|---|---|
| Single | A → B | ✅ |
| Multilevel | A → B → C | ✅ |
| Hierarchical | A → B, A → C | ✅ |
| Multiple | A, B → C | ❌ with classes (✅ with interfaces); ✅ in C++ and Python |
| Hybrid | mix | via interfaces |
The diamond problem
A (has show())
/ \
B C (both override show())
\ /
D → which show() does D get?
- Java avoids it by disallowing multiple class inheritance; with interfaces' default methods, D must override and choose (
B.super.show()). - C++ solves it with virtual inheritance.
- Python uses the MRO (method resolution order, C3 linearisation):
D.__mro__.
Composition over inheritance: prefer HAS-A (a Car has an Engine) when the relationship isn't truly IS-A. Deep inheritance trees become fragile.
4. Polymorphism
"Many forms" — the same method name does different things.
Compile-time (static) polymorphism — method overloading
Same name, different parameter lists, chosen by the compiler.
class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
Changing only the return type is not overloading (compile error). C++ also has operator overloading.
Runtime (dynamic) polymorphism — method overriding
A child redefines a parent method; which one runs is decided at runtime by the actual object type (dynamic dispatch).
Animal a = new Dog("Tommy"); // parent reference, child object
a.sound(); // "Tommy barks" — Dog's version, decided at runtime
a.eat(); // inherited from Animal
// a.fetch(); // ❌ compile error — the reference type Animal has no fetch()
List<Animal> zoo = List.of(new Dog("Tommy"), new Cat("Kitty"));
for (Animal x : zoo) x.sound(); // each animal makes its own sound
- C++ needs the
virtualkeyword for this (otherwise the reference type decides). Java methods are virtual by default. static,privateandfinalmethods can't be overridden.
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| Where | same class | parent and child |
| Parameters | must differ | must be the same |
| Return type | can differ | same (or a subtype — covariant) |
| Decided | compile time | runtime |
| Access modifier | any | can't be more restrictive |
The same idea in Python and C++
class Animal:
def sound(self): return "..."
class Dog(Animal):
def sound(self): return "barks" # overriding
for a in [Animal(), Dog()]:
print(a.sound()) # duck typing — any object with sound() works
class Animal { public: virtual void sound() { cout << "...\n"; } virtual ~Animal() {} };
class Dog : public Animal { public: void sound() override { cout << "barks\n"; } };
Animal* a = new Dog(); a->sound(); // barks (because of virtual)
delete a;
Interview one-liners
- Encapsulation hides data; abstraction hides complexity.
- Inheritance = IS-A and code reuse; composition = HAS-A and is often better.
- Overloading = compile-time polymorphism; overriding = runtime polymorphism.
- Java has no multiple inheritance of classes because of the diamond problem.
- Related: Classes, Objects, Constructors and Access Modifiers, SOLID Principles, Java OOP Concepts.