Back to journalNotes from the craft

Backend

What Is Object-Oriented Programming (OOP)?

Learn classes, objects, and the four core OOP concepts through a familiar example: cars and how they behave.

Nyi Nyi Zin

Software developer

What Is Object-Oriented Programming (OOP)?
On this page

As a project gains more data and functions, it can become difficult to track which function uses which data.

Object-oriented programming (OOP) is a way of organizing related data and behavior into objects.

Think about a car

A car has properties such as its color, model, and current speed. Behaviors such as driving and braking are called methods.

You can think of a class as a blueprint defining those properties and methods. Each individual car created from that class is an object.

For example, a Car class can be used to create a blue car and an orange car. They share the same class, but each object can have its own data.

Four core OOP concepts

1. Encapsulation: controlling access to data

Encapsulation keeps related data and methods together and controls how internal data is read or changed.

For example, instead of letting outside code change a car’s speed arbitrarily, you can require it to use methods such as accelerate() and brake().

2. Inheritance: extending an existing class

A class can inherit properties and methods from another class and add the behavior it needs.

For example, SportsCar can inherit from Car and add a method such as turboBoost().

3. Polymorphism: the same method, different behavior

Different objects can support the same method while carrying out the action in their own way.

For example, PetrolCar and ElectricCar can both provide start(). The method name is the same, but one starts a petrol engine while the other prepares an electric drive system.

4. Abstraction: exposing the operations people need

Abstraction hides internal details and provides a clear way to use the necessary behavior.

When driving, you can use the steering wheel, accelerator, and brakes without understanding every detail of how the engine works.

What OOP can help with

When applied appropriately, OOP can help you:

  • Keep related data and behavior together
  • Reuse and extend code
  • Separate the responsibilities that need to change
  • Make code structure easier for a team to understand

One thing to remember

Using OOP does not automatically make code better. You still need to define the responsibilities of your classes carefully.

Backend

Written by

Nyi Nyi Zin

I build for the web, mobile, and everything behind the scenes. This is where I share what I learn along the way.

More about me