In the previous two articles, we talked about programming language syntax. This article is also about syntax, but it is the first one in which we truly start thinking about how to architect our applications. We will learn about software architecture extensively in the intermediate track, when we learn about software systems.

But before we learn about systems: in the previous article we learned how to organize code into files and libraries, and now it's time to learn a new approach, object-oriented programming, where we organize our code into objects.

Object-oriented programming is usually abbreviated as OOP, and I will use this abbreviation often throughout the article.

Object-oriented programming is the most common way developers write code today. On a personal note, as someone who started developing in Java three decades ago, it is the only approach I have ever used, since Java is one of the languages in which there is no other way to code except object-oriented, as we will see later in this article.

Introduction: a different way to think about programming

Imagine following a recipe: chop three onions, heat the pan, add oil, stir for five minutes. That is how traditional programming works, a linear list of step-by-step instructions called procedural programming.

Now imagine walking into a busy restaurant kitchen. You do not micro-manage every movement of the staff. Instead, you have distinct people: the Head Chef, the Pastry Specialist, and the Waiter. Each person knows their own job, manages their own tools, and talks to the others by exchanging requests.

This shift, from running through a single list of commands to coordinating a team of specialized actors, is the core idea behind Object-Oriented Programming (OOP).

Instead of one long list of instructions, we build a world of small, independent "things" called objects. Each object holds its own information and knows how to do its own job. The program becomes a conversation between objects.

We shift from instructions to interactions.

Object-oriented programming encourages us to think about the things that exist in our system, what they know, what they can do, and how they interact with one another. It is a different way of organizing software.

And to understand it, we can begin with something familiar: the world around us.

The world is full of objects

Look around you. You probably see a table, a chair, a phone, or perhaps a car outside your window. Each of these things has characteristics and actions associated with it.

Think about a car. A car has characteristics such as:

  • Color
  • Model
  • Current speed
  • Fuel level

It can also perform actions such as:

  • Accelerate
  • Brake
  • Stop
  • Refuel

Now imagine that you own two cars. One is a red sports car, and the other is a blue family car. Both have the same kinds of characteristics and can perform similar actions, but their actual values are different.

Your red car might be traveling at 100 kilometers per hour, while your blue car is parked.

In programming, we can describe each car as an object. An object brings together two important things:

Data: information describing the object's current condition.

Behavior: actions the object can perform.

In programming terminology, the data is usually called attributes, properties, or fields, while the actions are called methods. A method is simply a function associated with an object.

This is the central idea behind object-oriented programming: organize related data and behavior into objects.

But before we see how programmers create these objects, let's explore where this idea came from.

How it started: ships, harbors, and two Norwegians

OOP was not invented in a big American lab. It started in Oslo, Norway, in the 1960s.

Two researchers at the Norwegian Computing Center, Ole-Johan Dahl and Kristen Nygaard, wanted to simulate real-world systems on a computer. Think of a harbor: ships arrive, wait for a free dock, unload cargo and leave. Each ship has its own name, size and cargo. Each dock is either free or busy.

Writing this as one long list of instructions was painful. So, they asked a simple question: why not describe each ship as a self-contained "thing" inside the program, with its own data and its own behavior? Their language, Simula 67, introduced the ideas we still use today: classes, objects and inheritance.

During the 1970s, researchers at Xerox PARC, including Alan Kay and his colleagues, developed another influential programming language called Smalltalk. Smalltalk expanded the object-oriented approach and placed objects and their interactions at the center of programming. Its philosophy emphasized that software could be built from objects communicating with one another.

The idea reached the mainstream when Bjarne Stroustrup, a Danish computer scientist working at Bell Labs, added classes to the popular C language. He started with "C with Classes" in 1979, renamed it C++ in 1983, and suddenly millions of C programmers could use objects.

In 1995, Java arrived, and OOP became the default way to build business software around the world.

Some languages, like Java, C# and Python, were created with object support from the start. Others adopted it later, for example JavaScript (it always had objects, but the class keyword arrived only in 2015).

One small note: in this section I mentioned two programming languages you haven't met before. The first is C++, the object-oriented extension of C.

The second is C# (pronounced "C sharp"). Microsoft introduced it in 2000, and as a Java developer I can't resist commenting: it borrowed a lot of Java concepts to compete with Java, after Sun Microsystems, Java's owner at the time, sued Microsoft over J++, Microsoft's own incompatible version of Java.

C# was born object-oriented, and it looks a lot like Java: if you can read one, you can almost read the other. It runs on Microsoft's .NET platform and powers Windows applications, large enterprise systems, web services and many video games built with the Unity game engine.

It's time to dive into OOP.

Classes and objects: the blueprint and the house

Two words sit at the heart of OOP: class and object.

A class is a blueprint. An architect draws one plan for a house: three bedrooms, a kitchen, a front door. The plan itself is not a house. You can't live in it.

An object is a real house built from that plan. From one blueprint, a builder can build 100 houses. They all share the same structure, but each has its own address, its own wall color and its own family living inside.

In software it works the same way. A class describes two things:

  • Attributes (also called properties or fields): what the object knows. A car knows its color, its brand and its current speed.
  • Methods: what the object can do. A car can start, accelerate and brake.

Here is a Car class in Python:

Python

"""
Define a new class called Car
"""
class Car:
    # constructor
    def __init__(self, brand, color):
        self.brand = brand   # what the car knows
        self.color = color
        self.speed = 0

    # what the car can do
    def accelerate(self, amount):
        self.speed = self.speed + amount

    # what the car can do
    def brake(self):
        self.speed = 0

And here we build two real cars (objects) from that one blueprint:

Python

# build a car of brand Toyota color red
my_car = Car("Toyota", "red")
# build a car of brand Tesla color white
your_car = Car("Tesla", "white")

# tell the Toyota to accelerate
my_car.accelerate(50)
print(my_car.speed)    # result 50
print(your_car.speed)  # result 0, your car didn't move

Notice that when my car speeds up, your car stays still. Each object has its own data, just like each house has its own family.

The special method __init__ is called a constructor. The next section will explain constructors.

The same class in Java looks a little more formal, but the idea is identical:

Java

/**
 * Define a class called Car
 */
public class Car {
    private String brand;
    private String color;
    private int speed = 0;

    /*
    constructor
    */
    public Car(String brand, String color) {
        this.brand = brand;
        this.color = color;
    }

    /*
    Method that increases the speed
    */
    public void accelerate(int amount) {
        speed = speed + amount;
    }
}

// Now let's create a new Car object
Car myCar = new Car("Toyota", "red");

The word new says it plainly: build me a new object from this blueprint.

Most programming languages have naming conventions: a set of rules for how to write the code. They are not syntax; the program will compile even if you don't follow them. They are an agreement that helps developers of the same language better understand each other's code.

For example, in Java all class names should start with a capital letter. If you look at the code, the class name is Car and not car; this is how I immediately know that Car is a class.

Did you spot another object in the code above? String! String is an object that has functions (methods) to handle text. In fact, in Java every basic variable type can be represented either as a "primitive," for example int, which holds just a value, or as an object, for example Integer which has helper methods to process int numbers. For example, doubleValue() converts the int value to a double (a decimal number).

Constructors and destructors: the birth and the goodbye of an object

Every object has a life story. It is born, it works, and one day it is no longer needed. Like a car: it rolls off the assembly line already painted in its color, it is driven for years, and in the end it goes to the scrapyard.

OOP gives us two special methods for the two ends of that story.

In the previous article we already met a function with a special name, the main() function. Now let's meet constructors and destructors.

We already met the constructor in the examples above: the method that runs automatically the moment an object is created.

Think of moving into a new apartment. Before you can live there, someone has to hand you the keys, connect the electricity and write your name on the mailbox.

The constructor does exactly that for an object: it sets the starting values and prepares everything the object needs.

Each language spells it a little differently:

Language How you write a constructor
PythonA method called __init__
Java, C#, C++A method with the same name as the class, like Car(...)
JavaScriptA method called constructor

A class can even have several constructors, each accepting different information. You can buy a car with the default color, or order one in a special color. Same car, two ways to be born:

Java

public class Car {
    private String color;

    // no details given
    public Car() {
        this.color = "white";
    }

    // the buyer chooses a color
    public Car(String color) {
        this.color = color;
    }
}

Car standard = new Car();        // a white car
Car special = new Car("blue");   // a blue car

The destructor: moving out

When you leave an apartment, you also have work to do: return the keys, disconnect the electricity, close the water. If you just disappear, the landlord is left with a mess.

Objects often hold resources too: an open file, a connection to a database, a chunk of the computer's memory. When an object's life ends, someone has to give those resources back. The method that does this is called a destructor.

Not all languages have destructors.

C++ is the classic language of destructors. In C++, as I explained in previous articles about C, the programmer is responsible for the computer's memory, so cleaning up is part of the job.

A destructor in C++ has the class name with a tilde (~) in front of it, and it runs automatically the moment the object's life ends.

Let's see a C++ example:

C++

#include <iostream>
using namespace std;

class Apartment {
public:
    // constructor: moving in
    Apartment() {
        cout << "Keys received, electricity connected" << endl;
    }
    // destructor: moving out
    ~Apartment() {
        cout << "Keys returned, electricity disconnected" << endl;
    }
};

int main() {
    {
        Apartment myHome;               // the constructor runs here
        cout << "Living happily..." << endl;
    }                                    // the destructor runs here, automatically
    return 0;
}
// Keys received, electricity connected
// Living happily...
// Keys returned, electricity disconnected

Most modern languages took a different road. Java, C#, Python and JavaScript have a garbage collector: a cleaning crew that walks around the program while it runs, finds objects nobody uses anymore, and throws them away.

The programmer doesn't need to free memory by hand. The price is that you never know exactly when the cleaning crew will arrive.

That's why these languages have weaker destructors, or none at all.

The four pillars of OOP

Classes and objects are the bricks. What makes OOP powerful are four ideas built on top of them. Programmers call them the four pillars. They are what make objects safe, flexible and easy to build:

  1. Encapsulation: each object guards its own data. Others can't reach inside and change it directly.
  2. Abstraction: show only what matters, hide the complicated details. You drive a car with a wheel and pedals, not by controlling the fuel injectors.
  3. Inheritance: build new classes on top of existing ones, and reuse what already works.
  4. Polymorphism: different objects respond to the same request, each in its own way.

Let's explain each one.

Encapsulation: every object guards its own data

Think about your bank account. Your balance is stored somewhere in the bank's computers. Can you walk into the bank, open the vault and write a new number on your balance sheet? Of course not.

You can only use the official windows: deposit, withdraw and check balance. The bank checks every request. Try to withdraw more than you have, and the bank says no.

That is encapsulation. The object wraps its data inside a protective "capsule" and exposes only a few safe doors.

Here is a bank account in Java:

Java

/*
 Class BankAccount
*/
public class BankAccount {
    // hidden inside the capsule
    private double balance = 0;

    /*
    Function to deposit money
    */
    public void deposit(double amount) {
        // the bank checks that the amount is valid
        if (amount > 0) {
            balance = balance + amount;
        }
    }

    /*
    Function to withdraw money
    */
    public boolean withdraw(double amount) {
        // the bank checks that you have enough money
        if (amount <= balance) {
            balance = balance - amount;
            return true;
        }
        return false; // not enough money
    }

    /*
    Function to get your balance
    */
    public double getBalance() {
        return balance;
    }
}

Now nobody can write account.balance = 1000000. The program won't even run. The only way to change the balance is through deposit and withdraw, and both of them check the rules first.

On the above example you met a special return value: void.

public void deposit(double amount) {

void simply means: nothing, this function doesn't return anything. We use void and not zero, since zero is a number, for example a function calculating 2-2 will return zero, void returns nothing.

Access control: public, private, and protected

In the example above, and in some examples from previous articles, you have seen the words private and public.

The words public and private in the example are called access modifiers. They decide who is allowed to see and use each part of a class.

A good way to picture them is a family home. Let's explain it with a house example:

Modifier Who can use it In the house
publicAnyone, anywhere in the programThe front porch: every guest is welcome
protectedThe class itself and its "children" (classes that inherit from it)The family kitchen: family members only
privateOnly the class itselfYour bedroom diary: nobody else, not even your kids

Not every language is this strict:

  • Python trusts programmers. It has no real private. Instead, a name that starts with an underscore, like _balance, is a polite sign that says "please don't touch." Two underscores, like __balance, make it harder (but not impossible) to reach.
  • JavaScript had no private data for most of its life. Since 2022, a # before a name, like #balance, makes it truly private.

The rule of thumb is simple: make everything private unless there's a good reason to share it. The fewer doors a house has, the easier it is to keep safe.

Abstraction: focus on what matters

You actually encountered the word abstraction in the previous article, where I explained functions.

Encapsulation and abstraction are closely related, but they are not the same thing. Encapsulation is concerned with packaging data and behavior and controlling access. Abstraction is concerned with hiding unnecessary complexity and presenting only the essential capabilities.

Let's return to our car. When you drive, you interact with a steering wheel, accelerator, and brake pedal. You don't need to understand every mechanical and electronic process happening beneath the hood.

The car presents a simplified set of controls. This is abstraction.

In software, abstraction allows programmers to work with a simple description of what something does without needing to know all the details of how it works.

Consider a printer. A program might ask:

printer.print(document)

The program does not need to understand how the printer moves paper, controls ink, or communicates with its internal electronics. It only needs to know how to request printing.

Abstraction is extremely valuable because it allows complex systems to be built from simpler building blocks.

Inheritance: children that inherit from their parents

Children inherit things from their parents: eye color, a family name, sometimes a house. They also have traits of their own that their parents never had.

Classes can do the same. Imagine we are building a program for a zoo. All animals have a name and an age. All animals eat and sleep. Writing these same lines again and again for lions, dogs, parrots and penguins would be a waste. Instead, we write them once, in a general Animal class, and let every specific animal inherit from it.

Let's see the code in Java. Here the word extends means "inherits from":

Java

/*
The parent class Animal
*/
public class Animal {
    // the protected keyword means every class that inherits from this class has access
    protected String name;
    protected int age;

    //parent constructor receives name and age
    public Animal(String name, int age) {
        // the keyword "this" means the variable named "name" defined in this class
        // we need it to tell apart the variable defined in this class
        // from the variable "name" we received as a parameter of this function
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println(name + " is eating");
    }

    public void sleep() {
        System.out.println(name + " is sleeping");
    }
}

Java

/*
Class Dog inherits from class Animal
*/
public class Dog extends Animal {
    //class Dog constructor
    public Dog(String name, int age) {
        // super means call the parent constructor to set up name and age
        super(name, age);
    }

    /*
    The method fetch() belongs only to Dog, not to Animal
    */
    public void fetch() {
        System.out.println(name + " brings back the ball");
    }
}

Dog rex = new Dog("Rex", 3);
rex.eat();      // Rex is eating (inherited from Animal)
rex.fetch();    // Rex brings back the ball (Dog's own skill)

Notice the word super. It is the child saying to its parent: "you already know how to set up a name and an age, please do it for me." Notice also that name is protected: the family kitchen from the access control section. The Dog child can use it, strangers cannot.

Let's see this example in Python:

Python

# The parent class
class Animal:
    # the parent constructor
    def __init__(self, name, age):
        # Python uses self where Java uses this
        self.name = name
        self.age = age

    def eat(self):
        print(self.name + " is eating")

    def sleep(self):
        print(self.name + " is sleeping")

Python

"""
Dog inherits from Animal.
In Python, to say Dog inherits from Animal, we write the parent's name in brackets: Dog(Animal)
"""
class Dog(Animal):
    def fetch(self):
        print(self.name + " brings back the ball")

class Bird(Animal):   # Bird inherits from Animal
    def fly(self):
        print(self.name + " flies away")

The Dog class never wrote a word about eating or sleeping, yet it can do both:

Python

rex = Dog("Rex", 3)
rex.eat()      # Rex is eating (inherited from Animal)
rex.fetch()    # Rex brings back the ball (Dog's own skill)

Let's see the same example in the two new languages I introduced in this article, C++ and C#.

C++

#include <iostream>
#include <string>
using namespace std;

/*
Parent class Animal
*/
class Animal {
protected:
    string name;
    int age;
public:
    Animal(string name, int age) : name(name), age(age) {}

    void eat() {
        cout << name << " is eating" << endl;
    }
    void sleep() {
        cout << name << " is sleeping" << endl;
    }
};

/*
In C++ we use : to say that class Dog inherits from class Animal
*/
class Dog : public Animal {
public:
    //call the parent constructor
    Dog(string name, int age) : Animal(name, age) {}

    void fetch() {
        cout << name << " brings back the ball" << endl;
    }
};

int main() {
    Dog rex("Rex", 3);
    rex.eat();     // Rex is eating (inherited from Animal)
    rex.fetch();   // Rex brings back the ball (Dog's own skill)
    return 0;
}

C#

/*
Parent class Animal
*/
public class Animal
{
    protected string name;
    protected int age;

    // constructor
    public Animal(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public void Eat()
    {
        Console.WriteLine(name + " is eating");
    }

    public void Sleep()
    {
        Console.WriteLine(name + " is sleeping");
    }
}

/*
C# also uses : to say Dog inherits from Animal
*/
public class Dog : Animal
{
    //call the parent constructor
    public Dog(string name, int age) : base(name, age) { }

    public void Fetch()
    {
        Console.WriteLine(name + " brings back the ball");
    }
}

Dog rex = new Dog("Rex", 3);
rex.Eat();      // Rex is eating (inherited from Animal)
rex.Fetch();    // Rex brings back the ball (Dog's own skill)

As you can see, C# is really similar to Java, with a few differences. It uses a colon (:) instead of the word extends, and its naming conventions are different: C# programmers write method names with a capital letter (Eat, Fetch), while Java programmers start with a small one (eat, fetch).

Another difference: Java programmers put the opening curly bracket at the end of the line, e.g. public class Animal {, while C# developers put it on a new line:

public class Animal
{

When I was an engineering manager interviewing candidates for a Java developer position, if I saw a candidate write the brackets on a new line, I immediately knew he grew up on C# and was not a true Java disciple.

Same idea, different house rules.

The parent is called the base class (or superclass). The children are derived classes (or subclasses). A child can also override what it inherited, replacing the parent's version with its own. We'll see why that matters in a moment, when we reach polymorphism.

Inheritance describes an "is-a" relationship

A useful way to recognize inheritance is to ask whether one thing is a type of another thing.

A sports car is a car. An electric car is a car. Therefore, it makes sense for these specialized classes to inherit from Car.

However, an engine is not a type of car. An engine is a part of a car. That distinction will become important when we discuss composition later.

Interfaces: agreeing on a common language

So far, we have seen how classes can inherit behavior from other classes. But what happens when completely different objects need to provide the same capability?

Imagine that we have a car, a motorcycle, and a bicycle. They are different types of vehicles. But all of them can stop. Perhaps our software needs to control any object capable of braking.

We could define a common agreement: "Any object that claims to be brakeable must provide a brake() method."

In object-oriented programming, this kind of agreement is often represented by an interface. An interface defines capabilities that a class promises to provide. It describes what an object must be able to do, without necessarily specifying exactly how it should do it.

Agreements are a key concept in software. In this article we talk about agreements between objects, but we will meet them again later in this basic track when I talk about communication, and in the intermediate track, where I will teach distributed systems, we will talk about APIs (Application Programming Interfaces): the contracts between two different applications.

Example in Java:

Java

/*
Declare an interface called Brakeable
*/
interface Brakeable {
    void brake();
}

This interface declares that any class implementing Brakeable must provide the required brake() behavior.

Now consider two classes.

Java

/*
This class implements the Brakeable interface
meaning it must provide the method brake()
*/
class Car implements Brakeable {
    public void brake() {
        System.out.println("Car applies brakes");
    }
}

class Bicycle implements Brakeable {
    public void brake() {
        System.out.println("Bicycle applies brakes");
    }
}

Both classes implement the same interface. But their braking mechanisms are different. The car uses its braking system, while the bicycle uses its hand brake.

Our software does not need to know how each vehicle stops. It only needs to know that both support the Brakeable interface.

Interfaces are also very useful when designing a big system: instead of jumping straight into coding the classes and objects, you can start by designing the interfaces, which define how the objects will communicate and who will call whom.

Interfaces and inheritance: what is the difference?

Inheritance is commonly used to describe what something is. An electric car is a car.

An interface describes what something can do. A car can be brakeable. A bicycle can be brakeable. And a completely different object might implement the same interface if that capability makes sense.

Interfaces are especially useful when different classes must cooperate without sharing the same parent class. They also support polymorphism because software can work with an object through its interface rather than depending on its exact class.

Polymorphism: one request, many answers

"Polymorphism" sounds frightening, but it is just Greek for "many shapes."

In the past, when I interviewed candidates who had just graduated from university, they didn't have practical experience to show me yet, so I usually asked a lot of theory questions. In particular, I asked them to explain what polymorphism is and to give examples. I was always surprised how many of them struggled with the answer, even though it's really a simple idea.

Imagine a theater director shouting: "Perform your act!"

  • The singer sings.
  • The magician pulls a rabbit out of a hat.
  • The acrobat does a backflip.

The director does not need to learn three different commands (sing(), doMagicTrick(), doBackflip()). They issue one command, perform(), and each artist knows how to execute it based on who they are.

Polymorphism allows different types of objects to respond to the same operation in their own way.

In code, polymorphism means you can send the same message to different objects, and each object responds in its own way.

Let's look at a zoo example in Python:

Python

# parent class Animal
class Animal:
    def make_sound(self):
        print("...")

# class Dog inherits from Animal
class Dog(Animal):
    # this is called overriding a method
    # the child class replaces the parent method's implementation
    # with its own implementation, the sound of a dog
    def make_sound(self):   # override the parent's version
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

class Cow(Animal):
    def make_sound(self):
        print("Moo!")

rex = Dog()
kitty = Cat()
edna = Cow()

rex.make_sound()
kitty.make_sound()
edna.make_sound()

Output

Woof!
Meow!
Moo!

How objects talk to each other

Back to our restaurant. A customer sits down. The waiter takes the order and passes it to the chef. The chef cooks and tells the waiter the food is ready. At the end, the waiter asks the cashier for the bill.

Nobody does someone else's job, and nobody reaches into someone else's kitchen. They just send messages.

Objects work exactly like that. When one object needs something from another, it calls one of its public methods. Alan Kay, the father of Smalltalk, always said this was the most important idea in OOP: not the classes, but the messages between them.

Solid arrows are requests, dashed arrows are the responses that come back. The customer only ever talks to the waiter.

The customer only talks to the waiter; the waiter passes each message to the object that knows how to handle it.

In code, the conversation looks like this:

Java

public class Chef {
    public String cook(String dish) {
        return "a hot plate of " + dish;
    }
}

public class Cashier {
    public String makeBill(String dish) {
        return "Bill for " + dish + ": 60 dollars";
    }
}

public class Waiter {
    private Chef chef;        // the waiter knows the chef
    private Cashier cashier;  // and the cashier

    public Waiter(Chef chef, Cashier cashier) {
        this.chef = chef;
        this.cashier = cashier;
    }

    public String takeOrder(String dish) {
        String food = chef.cook(dish);          // message to the chef
        String bill = cashier.makeBill(dish);   // message to the cashier
        return food + " | " + bill;
    }
}

Java

Waiter waiter = new Waiter(new Chef(), new Cashier());
System.out.println(waiter.takeOrder("pasta"));
// a hot plate of pasta | Bill for pasta: 60 dollars

The waiter has no idea how the chef cooks. If the restaurant hires a new chef with a completely different technique, the waiter doesn't change at all, as long as the new chef still answers to cook.

In the previous example, the waiter object contained a Chef object and a Cashier object. This introduces another important object-oriented design technique: composition.

Composition means building a more complex object by combining simpler objects.

Think about a real car. A car contains:

  • An engine
  • A transmission
  • A braking system
  • A fuel or battery system

These components work together to form a complete vehicle. We can organize software in the same way. Rather than building one enormous Car class containing every possible detail, we can create separate classes for different responsibilities. The car then uses these components.

"Composition over inheritance."

Inheritance is tempting, and beginners often overuse it. They build family trees ten levels deep, and a small change at the top shakes the whole tree. Experienced programmers follow a famous piece of advice: prefer building objects from smaller parts ("has a") over inheriting from long chains of parents ("is a").

A robot that has arms, legs and a camera is easier to change than a robot that inherits from Machine, which inherits from MovingThing, which inherits from Thing.

Why OOP took over the world, and where it struggles

OOP became the most common way to build large software for one main reason: it lets many people build very big things without stepping on each other's toes. Here is what it gives us:

  • Organization. Code is split into clear, named pieces. Looking for how payments work? Open the Payment classes. You don't have to read the whole recipe book.
  • Reuse. Write it once in a parent class, use it in a hundred children. Or take a ready-made class from a library and use it as is.
  • Safety. Encapsulation protects data from accidental changes. The bank balance can only change through the bank's rules.
  • Easier change. Thanks to polymorphism and interfaces, you can add a new vehicle, a new animal or a new chef without touching the code that already works.
  • Teamwork. One team builds the Chef, another builds the Waiter. As long as both teams respect the agreed methods, they can work in parallel.
  • Closer to how we think. People naturally think in "things": customers, orders, cars. OOP lets the code speak the same language as the business it serves, so programmers and non-programmers can discuss the same model.

But OOP is not magic, and it has its critics:

  • Over-engineering. It is easy to create too many classes, too many layers and too many family trees for a simple problem. Sometimes a 20-line script is all you need.
  • Deep inheritance trees. A change in a grandparent class can break a great-grandchild somewhere far away. This is why "composition over inheritance" became such popular advice.
  • Hidden complexity. When objects call objects that call other objects, following what really happens can feel like a treasure hunt.
  • Not every problem fits. Some tasks, like processing huge streams of data, are more naturally described as a series of transformations. For those, another style called functional programming often shines.

OOP is not the only way to think about code, but it remains the backbone of most business software in the world: banking systems, insurance platforms, mobile apps and online stores.

Wrapping up: from a recipe book to a team

We started with one giant recipe book and ended with a restaurant full of people who each know their job and talk to each other. That is the journey OOP took software on, starting with two Norwegians simulating ships in a harbor.

Here is everything in one place:

Idea In one sentence Everyday picture
ClassA blueprint that describes what something knows and doesAn architect's house plan
ObjectA real thing built from a class, with its own dataOne house built from the plan
EncapsulationAn object guards its data and exposes only safe doorsThe bank's service window
Access controlpublic, protected and private decide who can see whatFront porch, family kitchen, bedroom diary
AbstractionShow only what matters and hide the complicated detailsA car's steering wheel and pedals
InheritanceA new class reuses and extends an existing oneChildren inheriting from parents
InterfaceA contract that says what a class must do, not howA car and a bicycle can both brake
PolymorphismOne request, and each object answers in its own wayThe director's "Perform your act!"
MessagesObjects cooperate by calling each other's methodsWaiter, chef and cashier

The next time you tap a button on your phone, add a product to an online cart or pay with your credit card, remember: behind the screen, a small society of objects is having a conversation, each one doing its job and trusting the others to do theirs.