Find a course

Module 1: Thinking in ObjectsLesson 1 of 1212 min

Why Objects? From Loose Data to Models

See why programs that keep data and behavior together in objects stay easier to change than code built on loose variables and parallel arrays.

Step 1 of 14Learn

Two hundred enemies and four arrays

Jordan is building a small arcade game. The first version tracks enemies with four arrays: xs, ys, healths and speeds. Enemy number 17 is xs[17], ys[17], healths[17] and speeds[17]. It works fine for a week.

Then the bugs start. A function that removes dead enemies deletes from healths but forgets speeds, so every enemy after number 17 now moves at its neighbor's speed. A new enemy type needs a shield value, which means a fifth array and edits in nine places. Nobody can say which functions are allowed to change healths, because any code anywhere can.

The problem isn't Jordan's skill. It's the shape of the code: data that belongs together is stored apart, and the rules for changing it are scattered.

Object-oriented programming (OOP) fixes the shape. Instead of four arrays, Jordan writes one Enemy type. Each enemy object carries its own position, health and speed, and the code that changes an enemy lives right next to that data: enemy.takeDamage(10), enemy.move(). Removing an enemy removes one object, so nothing can drift out of sync. Adding a shield means editing one class.

This course teaches that way of thinking: how to model a problem as objects, how to protect their data, how to share and vary behavior, and how to design classes that stay easy to change. Examples use JavaScript, with Python shown where the syntax differs, but the ideas carry over to Java, C#, C++, Kotlin, Swift and most modern languages.

Step 2 of 14Learn

State and behavior

An object bundles two things:

  • State: the data it remembers, stored in fields (also called properties or attributes). An enemy's state is its position, health and speed.
  • Behavior: what it can do, written as methods, which are functions attached to the object. An enemy can move(), takeDamage(amount) and report isAlive().

Here's the enemy as a single object literal in JavaScript:

const enemy = {
  x: 40, y: 12, health: 100, speed: 2,
  move() { this.x += this.speed; },
  takeDamage(amount) { this.health = Math.max(0, this.health - amount); },
  isAlive() { return this.health > 0; }
};
enemy.takeDamage(30);   // health is now 70

Notice the word this. Inside a method, this means "the object the method was called on". When you write enemy.takeDamage(30), this is enemy, so the method changes that enemy's health and nobody else's.

A useful test for whether something should be an object: does it have identity (two enemies with the same numbers are still two different enemies), state that changes over time, and rules about how that state may change? If all three are true, an object is usually a good fit. A plain value such as the number 7 or the string "red" doesn't need any of that.

Step 3 of 14Practice · Sort into groups

Sort each item: is it state (data an object remembers) or behavior (something it does)?

Tap an item, then tap its group (or drag it there).

Step 4 of 14Practice · Diagram

One enemy object: state and behavior together

Which member is the rule-keeper for health?

Tap the shape that answers the question, then press Check.

One enemy object: state and behavior togetherParts diagram: enemy, x, y, health, speed, move(), takeDamage(amount), isAlive().enemyx, yhealthspeedmove()takeDamage(-amount)isAlive()
enemy
x, y

State: where the enemy is.

health

State: changes only through takeDamage().

speed
move()

Behavior: uses this.speed to change this.x.

takeDamage(amount)

Behavior: the only place health goes down, never below 0.

isAlive()

Behavior: answers a question without changing anything.

Step 5 of 14Learn

The four pillars, in plain words

OOP is often summarized by four ideas. You'll study each in depth, but it helps to see the whole map first.

  1. Encapsulation: an object hides its internal data and exposes a small set of methods for working with it. A bank account doesn't let outside code set the balance directly; it offers deposit() and withdraw(), which enforce the rules.
  2. Abstraction: you work with an object through what it does, not how it does it. You call list.sort() without caring which sorting algorithm runs inside.
  3. Inheritance: a class can be built on top of another, reusing its fields and methods and adding or changing some. A SavingsAccount can extend Account and add interest.
  4. Polymorphism: different objects can respond to the same message in their own way. Call shape.area() on a circle or a square and each computes its area correctly, while the calling code stays the same.

Encapsulation and abstraction are closely related: encapsulation is the mechanism (hiding), abstraction is the benefit (a simpler way to think). Inheritance is the pillar most often overused; later you'll learn why many designers prefer composition, building objects out of other objects.

Step 6 of 14Practice · Match the pairs

Match each OOP pillar to the situation that shows it best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

Step 7 of 14Practice · Diagram

How the four pillars relate

Which pillar is the hiding mechanism that makes abstraction possible?

Tap the shape that answers the question, then press Check.

How the four pillars relateTwo-by-two matrix: Abstraction, Polymorphism, Encapsulation, Inheritance.AbstractionPolymorphismEncapsulationInheritanceWhat it is abouthiding detailssharing and varying behaviorRolemechanismbenefit
Abstraction

Think about what an object does, not how.

Polymorphism

One call, many behaviors; calling code stays the same.

Encapsulation

Private data behind a small set of methods.

Inheritance

Build a class on another to reuse and vary it. Often overused.

Step 8 of 14Compare

Procedural vs. object-oriented: the same task

AspectProcedural styleObject-oriented style
Where data livesIn separate variables or arrays passed around between functionsInside objects, next to the methods that use it
Changing dataAny function can change any data it receivesOnly the object's own methods change its fields
Adding a new kind of thingAdd branches to every function that handles kinds (if type === ...)Add a new class with the same methods
Good fitShort scripts, data pipelines, math-heavy codeLong-lived systems with many interacting things: games, apps, simulations

Step 9 of 14Note

Step 10 of 14Learn

Where OOP came from, and where you already use it

Object-oriented ideas are older than most people expect. In the 1960s, Norwegian researchers built a language called Simula to write simulations of ships, queues and factories, and they found it natural to model each real-world thing as an object with its own data and procedures. In the 1970s, the Smalltalk team pushed the idea further: everything is an object, and objects communicate only by sending each other messages. C++ brought classes to systems programming in the 1980s, and Java made OOP the default for a generation of business software in the 1990s.

You already use objects every day, even if you have never written a class. In JavaScript, "hello".toUpperCase() calls a method on a string object, and [3, 1, 2].sort() calls a method on an array object. In Python, my_list.append(4) and "a,b".split(",") do the same. The browser's document, a date created with new Date(), a Map, a file handle: all objects with state and methods.

Learning OOP properly means moving from using objects that others designed to designing your own: deciding what objects a problem needs, what each one should know, and what each one should be allowed to do.

Step 11 of 14Timeline

Where OOP came from

  1. 1960s
    Simula

    Norwegian researchers model ships, queues and factories as objects.

  2. 1970s
    Smalltalk

    Everything is an object; objects talk by sending messages.

  3. 1980s
    C++

    Classes come to systems programming.

  4. 1990s
    Java

    OOP becomes the default for business software.

  5. Today
    Objects everywhere

    JavaScript, Python, C#, Kotlin and Swift all mix objects with functions.

Step 12 of 14Practice · Select all that apply

Which of these lines call a method on an object? Select all that apply.

Select all that apply.

Step 13 of 14Practice · True or false

In OOP, a method is simply a function that is attached to an object and can work with that object's data.

Step 14 of 14Practice · Choose one

Jordan's game stores enemies in four parallel arrays. Which bug is this design most likely to cause?