OOP: the four pillars

Object-oriented programming organises code into objects that bundle data and behaviour. Its four pillars are encapsulation, abstraction, inheritance and polymorphism.

Why it matters

Large programs written as one long list of functions and shared variables become impossible to change safely. OOP groups data with the code that's allowed to change it.

The idea

Encapsulation hides an object's internal data behind methods, so it can't be put into an invalid state. Abstraction shows callers only what they need. Inheritance lets one class reuse and extend another. Polymorphism lets different classes be used through the same interface, each behaving in its own way.

A car. You use the steering wheel and pedals (abstraction) without touching the engine (encapsulation). An electric car is a kind of car (inheritance), and 'press the accelerator' works differently in each (polymorphism).

Cars are physical and their family tree is shallow. In code, inheritance is easy to overuse: deep class trees become fragile, which is why composition is often the better choice.

How it works

  1. Group related data and behaviour into a class: a BankAccount holds a balance and has deposit() and withdraw().
  2. Make the balance private, and have withdraw() check there's enough money first. That's encapsulation.
  3. Callers only see deposit(), withdraw() and the balance. That's abstraction.
  4. A SavingsAccount is a kind of BankAccount that also adds interest. That's inheritance.
  5. Code that loops over all accounts and calls monthly_update() gets the right behaviour for each type. That's polymorphism.

Example

A payment system: an abstract PaymentMethod with pay(amount); CardPayment and PayPalPayment each implement it differently; checkout simply calls method.pay(amount) without caring which one it has.

Key points

Common mistakes

Not true: Public fields: fine, as long as other code sets sensible values.
In fact: Nothing then stops other code from setting an invalid value, such as a negative balance. Keep the state private and change it through methods that check it.

In the interview

Encapsulation protects an object's state. Abstraction exposes only what callers need. Inheritance models an 'is-a' relationship to reuse behaviour. Polymorphism lets code work with an interface while each class supplies its own behaviour, like checkout calling pay() on any payment method.

Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.