Object Oriented Programming Explained: How Objects Tame Messy Code

Diagram of OOP basics: a class blueprint creating objects, with labels for encapsulation, inheritance and polymorphism

Object oriented programming (OOP) is a way of organizing code around objects, which are small units that hold their own data and know how to act on it. A player, a bank account or a shopping cart can each be an object living inside your program.

That one idea changes how big software gets built. This guide covers why OOP exists, how classes and objects work, and the three big ideas of encapsulation, inheritance and polymorphism. It then walks through a real online shop and the traps that undo all the benefits. These four terms sound intimidating, and by the end they should feel obvious.

TL;DR
  • OOP bundles data (fields) and behavior (methods) into objects.
  • A class is the blueprint, and objects are the real things built from it.
  • Encapsulation protects data, inheritance reuses code, and polymorphism lets one call behave differently per object.
  • Deep inheritance chains and giant 'god' classes recreate the mess OOP was meant to fix.
  • Keep objects small, give each one a single job, and prefer composition.
  1. 0:00Intro
  2. 0:31When code turns into spaghetti
  3. 1:22Bundle data and behavior together
  4. 2:14Big programs needed better organization
  5. 3:08A class is a blueprint
  6. 3:57Building an object, step by step
  7. 4:38Encapsulation keeps data private
  8. 5:31Inheritance reuses what already works
  9. 6:26Same call, different behavior
  10. 7:23Three ideas, one toolkit
  11. 8:07OOP is everywhere you look
  12. 9:01Inside an online shop
  13. 9:50Where OOP goes wrong
  14. 10:46Keep objects small and focused
  15. 11:28OOP in six simple ideas
  16. 12:00Small, focused objects beat tangled code

Why does code turn into spaghetti?

Fifty lines of code fit in your head. Real software doesn't. As a project grows, nobody remembers which piece does what, or why it's even there. That's the wall every programmer eventually hits.

Picture this. You fix a tiny bug in your game's health system, and the shop suddenly stops working. That happens when any part of the code can reach in and change anything else. One variable is shared by many functions, so a harmless edit spreads outward, and you only find out when users start complaining.

The damage isn't only technical. Teams working on messy codebases can spend days just figuring out where things live. Every hour spent hunting bugs is an hour not spent building features. Once a program gets large, structure stops being optional. OOP exists to stop this kind of chaos.

  • Hidden connections: change one thing and unrelated features quietly break
  • Scattered data: no single place to look when something goes wrong
  • Slow teams: more debugging, less building

What is object oriented programming?

The old approach leaves you with one big pile of variables and a separate pile of functions. OOP groups them together. Each object carries its own information and knows how to do its own jobs.

Think of a real car. It has facts about it, like its color and current speed. It can also do things, like accelerate and brake. A code object is that same combination. The data side is called fields or attributes, such as a player's name, health and position. The behavior side is called methods, which are functions that belong to the object, such as jump(), deposit() or addToCart().

This grouping matters because separating data from functions stopped working as programs grew. When everything about a user lives inside one user object, you know exactly where to look, and a fix happens in one place. Objects also match how people already think. A shop has customers, carts and products, so the code has customer, cart and product objects. Clear boundaries also let one developer build the cart while another builds payments.

  • Object = data + behavior
  • Fields hold what an object knows
  • Methods define what an object does
  • At its core, OOP is a way to manage complexity

What's the difference between a class and an object?

Beginners mix these two up all the time, so here's the simplest way to remember it. A class is the plan, and you write it once. Objects are the real things you create from that plan, as many as you need. In the Python example below, the class Dog says every dog has a name and can bark. The last line builds one actual dog called Rex.

An architect's house plan works the same way. It shows where the rooms and doors go, but you can't sleep in a drawing. Every house built from that plan is an object, and each can have its own paint and furniture. They share one blueprint but are separate things.

Here's what happens when Python runs rex = Dog('Rex'). It finds the Dog blueprint, creates a brand new empty Dog object, then runs the __init__ method to set the name to Rex. Calling rex.bark() prints "Rex says woof." Create Dog('Bella') next, and she gets her own copy of the data. Renaming Rex never affects Bella. That independence is what makes objects safe to use.

  • Find the class, which is the blueprint
  • Make a new, empty object
  • Run __init__ to fill in its data
  • Call methods on the finished object
class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        print(self.name + ' says woof')
rex = Dog('Rex')

What is encapsulation and why does it matter?

Objects hold data. But if any code can change that data however it likes, you're back to spaghetti. Encapsulation fixes this by keeping an object's data private, like a locked box. Outside code can't reach in. It has to go through a few approved methods that the object chooses to offer.

Look at the bank account below. The double underscore marks the balance as private. The only way to add money is the deposit method, and it checks the amount first, so nobody can slip in a negative number. Without encapsulation, any line anywhere could set the balance to a million dollars. With it, the account protects itself, and because the rules live inside the object, they can't be skipped.

A TV remote is a good comparison. You press volume up without ever touching the circuit board. Good objects work the same way, with simple controls outside and complex details hidden inside. The result is that bugs stay contained and the code is safer to change.

class BankAccount:
    def __init__(self):
        self.__balance = 0
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

How does inheritance work in OOP?

Inheritance lets a new class borrow everything from an existing one and then add its own twist. Imagine a game with zombies, skeletons and dragons. All of them have health, and all of them can move and take damage. Writing that code three times is wasteful and hard to keep in sync.

Instead, you write one Enemy class with health, move and take damage. Zombie, Skeleton and Dragon inherit all of it automatically. Each one only adds what makes it different. A Dragon, for example, adds fly() on top.

The parent class, also called the base class or superclass, holds the shared code. Fix a bug in its move method once, and every enemy in the game gets the fix. The child class, or subclass, is saying "I'm an Enemy, plus a bit more." The payoff is less copying and one place for shared fixes.

  • Parent (base class / superclass): shared code
  • Child (subclass): inherits everything, then extends it
  • One fix in the parent reaches every child

What is polymorphism, in plain English?

Polymorphism is the most intimidating-sounding word in OOP, and it literally means "many forms." You send the same message to different objects, and each one responds in the way that makes sense for it. Your code doesn't need to know which type it's talking to.

Say a game loop sends one instruction: draw(). The circle draws a curve, the square draws four edges, and the triangle draws three. Without polymorphism, you'd write long chains of checks like "is this a circle? is it a square?" and edit them every time a new shape appears. With polymorphism, you call draw() and trust the object. Add a Star class with its own draw(), and the game loop handles it without a single change.

These three pillars aren't competing options. They work together. Encapsulation protects data, inheritance reuses code, and polymorphism adds flexibility. One Dragon object can inherit from Enemy, keep its health private, and draw itself its own way, all at the same time.

  • Encapsulation: private fields, public methods, used to protect data
  • Inheritance: a child extends a parent, used to reuse code
  • Polymorphism: same method, many forms, used for flexible behavior

Where is object oriented programming used?

Almost everywhere. Some of the world's most popular languages are built around objects. In Java, practically everything lives inside a class. Python is gentler, but even plain numbers are objects there. C++ combines classes with raw speed, which is why many game engines are built with it.

In games, every player, enemy and power-up is usually an object. Mobile apps work the same way, with buttons, screens and user profiles as objects. Behind most websites, the server is full of objects too, such as users, carts, orders and login sessions.

An online shop shows all three pillars at work. The Customer adds items to the Cart, the Cart asks each Product for its price, and at checkout the Cart hands off to Payment. The Cart keeps its item list private, which is encapsulation. CardPayment and WalletPayment share a Payment parent, which is inheritance. Checkout calls pay() without caring which kind of payment it is, which is polymorphism. Each object owns one job, and none does another's work.

Common OOP mistakes and how to avoid them

OOP is powerful, and beginners often overdo it. Both of the most common mistakes start with good intentions, like wanting to reuse code or keep things in one place. Pushed too far, they bring back the exact mess OOP was supposed to fix.

The first trap is a deep inheritance chain, such as Animal → Pet → Dog → SmallDog → Puppy. To understand one puppy, you have to read four parent classes first, and a small change at the top can break something five levels down. Shallow trees of one or two levels are much safer. The second trap is the "god class," one class that handles users, emails, payments and reports at once. It's spaghetti code wearing a nicer outfit.

The fix is a simple habit. Give every object one clear job you can explain in a sentence. If the explanation needs "and" three times, split the class. A god class can become a UserManager, an EmailSender and a ReportBuilder, each small and easy to test. Instead of stacking inheritance deeper, combine objects. A Car has an Engine rather than being a kind of Engine. This is called composition, and it keeps family trees short.

  • Keep inheritance to one or two levels
  • One job per class
  • Prefer composition (has-a) over deep chains (is-a)

The bottom line

  • Objects bundle data and behavior together.
  • A class is the blueprint, and objects are built from it.
  • Encapsulation hides data behind safe methods.
  • Inheritance reuses and extends existing classes.
  • Polymorphism lets the same call behave differently for each object.
  • Small, focused objects keep code easy to change.

Quick-fire questions

What are the main pillars of object oriented programming?

The three pillars covered here are encapsulation, inheritance and polymorphism. Encapsulation protects data, inheritance reuses shared code, and polymorphism lets one method call work across different object types. Real programs use all three together.

Is a class the same thing as an object?

No. A class is the blueprint you write once, like a house plan. An object is a real instance built from that blueprint, and each object holds its own separate data.

Why use OOP instead of just writing functions?

As programs grow, keeping data in one place and functions in another makes it hard to know what affects what. OOP groups related data and behavior, so each object guards its own data and fixes happen in one spot. It also gives teams clear boundaries to split work along.

Which programming languages use OOP?

Java, Python and C++ are major examples. In Java, nearly everything lives in a class, and in Python even plain numbers are objects. C++ pairs classes with speed, which is why it's common in game engines.

What is a god class?

A god class is one class that tries to do everything, such as handling users, emails, payments and reports. It recreates spaghetti code inside a single object. The fix is to split it into smaller classes that each have one job.

What does 'composition over inheritance' mean?

It means building objects out of other objects instead of stacking deep inheritance chains. For example, a Car has an Engine and wheels rather than being a kind of Engine. This keeps class hierarchies short and easier to change.

Watch the full video on YouTube →

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad