Paradigms: objects, functions and types · Part 10 of 36

Object-oriented programming: classes and objects

Intermediate 16 min

Classes, objects, encapsulation, inheritance and composition — with the same example in JavaScript and Python.

What you will learn

  • You can define a class with a constructor, fields and methods in both languages.
  • You can explain encapsulation, inheritance and polymorphism.
  • You can say when composition is better than inheritance.

Before this: Functions: name a piece of work

Bundling data with behaviour

Object-oriented programming (OOP) groups data and the functions that work on it into objects. A class is the blueprint; each object made from it is an instance with its own data.

// JavaScript
class Bed {
  #plants = [];                    // private field
  constructor(name, areaM2) {
    this.name = name;
    this.areaM2 = areaM2;
  }
  plant(crop) { this.#plants.push(crop); }
  get count() { return this.#plants.length; }
}
const north = new Bed("north", 3.6);
north.plant("kale");
console.log(north.count);          // 1
# Python
class Bed:
    def __init__(self, name, area_m2):
        self.name = name
        self.area_m2 = area_m2
        self._plants = []          # "private" by convention

    def plant(self, crop):
        self._plants.append(crop)

    @property
    def count(self):
        return len(self._plants)

north = Bed("north", 3.6)
north.plant("kale")
print(north.count)                 # 1

The constructor (constructor / __init__) sets up a new object. Methods are functions that belong to the class; inside them, this (JavaScript) or self (Python) is the object the method was called on.

A cookie cutter and several cookies made from it

The three classic ideas

  1. Encapsulation. An object hides its inner details and offers a small public interface. JavaScript has truly private #fields (since ES2022); Python relies on the convention that names starting with _ are internal.
  2. Inheritance. A class can extend another and reuse its code: class RaisedBed extends Bed / class RaisedBed(Bed). The child can override methods and call the parent's version with super.
  3. Polymorphism. Different classes offer the same method name, and calling code doesn't care which one it has: every shape has area(), whether it is a circle or a rectangle. Python calls this "duck typing": if it has area(), you can use it as a shape.

Composition over inheritance

Inheritance looks elegant in textbooks but creates tight coupling: a change in the parent can break every child, and real things rarely fit one tree. ("Is a greenhouse bed a kind of bed, or a kind of greenhouse?") Most modern style guides prefer composition: an object has other objects and delegates to them.

class Bed:
    def __init__(self, name, irrigation):
        self.name = name
        self.irrigation = irrigation   # any object with water(litres)

    def water(self):
        self.irrigation.water(5)

Now you can swap a DripLine for a WateringCan without any class hierarchy — and in a test, pass a fake that just records the call.

When OOP shines

OOP fits naturally when you model things with state that changes over time and a clear identity: a document in an editor, a player in a game, a connection to a database. User-interface toolkits are classic examples. It fits less well for data pipelines that turn input into output — the domain where functional style, the next lesson, shines.

Try it: JavaScript sandbox

Write and run small JavaScript programs; the checker tells you when an exercise is solved.

Turn on JavaScript to use this lab. Worked example:

Exercise 10: write a class Counter with a method add() that increases a count and a getter value. The checker creates a counter, calls add() three times and expects value 3.

Key points

  • A class is a blueprint; objects are instances with their own data and shared methods.
  • this (JavaScript) and self (Python) refer to the current object.
  • Encapsulation hides internals; inheritance reuses code; polymorphism lets different classes share an interface.
  • Prefer composition ("has a") to deep inheritance ("is a") — it is easier to change and test.
  • OOP fits long-lived things with state and identity.

Flashcards

Question: What does a constructor do?
Answer: It initialises a new object (constructor in JavaScript, __init__ in Python).
Question: How do you mark a field truly private in JavaScript?
Answer: Start its name with # (since ES2022).
Question: What is polymorphism?
Answer: Different classes provide the same method, so calling code can treat them alike.
Question: Why prefer composition over inheritance?
Answer: It couples less: you can swap parts without a class hierarchy.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. In Python, what is self inside a method?

    • The object the method was called on
    • The class itself
    • The parent class
    • A global variable
    Show the answer

    The object the method was called on

    Python passes the instance as the first argument, named self by convention.

    Source: Python docs, 9.3 A First Look at Classes

  2. Match the OOP idea with its description.

    Show the answer

    Encapsulation = Hide internals behind a small interface; Inheritance = A class extends another and reuses its code; Polymorphism = Different classes share one interface

    These are the three classic OOP ideas.

    Source: MIT OCW 6.100L, OOP lectures

  3. A Bed object holds an irrigation object and calls its water() method. Which design is this?

    • Composition
    • Inheritance
    • Recursion
    • Overloading
    Show the answer

    Composition

    The bed has an irrigation part and delegates to it — composition.

    Source: MIT OCW 6.100L

  4. In JavaScript you create an instance with the keyword ___ Bed("north", 3.6).

    Show the answer

    new

    new calls the constructor and returns the new object.

    Source: MDN, Classes

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.