Classes & Objects
Classes & Object-Oriented Programming · Coding Fundamentals track
8 min read
In this module
Grouping Data and Behaviour
So far you've worked with individual variables and collections of data. Real-world concepts are messier than that. A "user" bundles a name, an email, an age, a list of permissions, and behaviours like "log in" and "change password." A "rectangle" is more than two numbers; it has a width and a height plus operations like "calculate area" and "resize."
Object-oriented programming (OOP) is a paradigm that lets you bundle related data and the functions operating on that data into a single unit. The blueprint for that unit is a class. A concrete instance of the class is an object.
class Dog { name breed age
function bark() { print(name + " says: Woof!") }
function describe() { print(name + " is a " + breed + ", age " + age) }}This class lays out what every Dog has (name, breed, age) and what every Dog can do (bark, describe). The class itself is just the blueprint, though.
Creating Objects
To get an actual dog, you instantiate the class:
my_dog = new Dog()my_dog.name = "Rex"my_dog.breed = "Labrador"my_dog.age = 3
my_dog.bark() // Rex says: Woof!my_dog.describe() // Rex is a Labrador, age 3Each object owns its own copy of the data fields. Spin up another Dog and it has its own name, breed, and age, independent of the first.
other_dog = new Dog()other_dog.name = "Luna"other_dog.breed = "Poodle"other_dog.age = 5
other_dog.bark() // Luna says: Woof!A class is a blueprint that defines data fields and methods. An object is an instance of a class with its own data. You can create many objects from one class, each with different values but the same structure and behaviour.
Constructors
Most languages give you a special method called a constructor that initialises an object's state at the moment of creation. Rather than setting fields one by one after the fact, the constructor takes the initial values as parameters and wires them up.
class Dog { name breed age
constructor(name, breed, age) { this.name = name this.breed = breed this.age = age }
function bark() { print(this.name + " says: Woof!") }}
my_dog = new Dog("Rex", "Labrador", 3)my_dog.bark() // Rex says: Woof!The keyword this (or self in some languages) refers to the current object — the specific instance whose method is being called right now.
Methods: Functions That Belong to Objects
Functions defined inside a class are called methods. They reach the object's data through this/self. Methods are the "behaviour" half of a class — they spell out what the object can do.
class BankAccount { owner balance
constructor(owner, initial_balance) { this.owner = owner this.balance = initial_balance }
function deposit(amount) { this.balance = this.balance + amount }
function withdraw(amount) { if amount > this.balance { print("Insufficient funds") return } this.balance = this.balance - amount }
function get_balance() { return this.balance }}Methods wrap up the logic that manipulates an object's state. Rather than poking at balance directly from the outside, you call deposit and withdraw, which can enforce rules — like refusing to let the balance go negative.
C has no classes, so it shows what a method boils down to. The struct holds the fields, and each "method" is an ordinary function whose first parameter is a pointer to the object, which is the this that OOP languages pass for you.
Objects in Memory
When you create an object, the system allocates a block of memory (usually on the heap) large enough for all the object's fields. The fields sit contiguously, much like a C struct.
my_dog = new Dog("Rex", "Labrador", 3)
Memory layout of my_dog:+--------+-----------+-----+| name | breed | age || "Rex" | "Labrador"| 3 |+--------+-----------+-----+The variable my_dog is actually a reference (a pointer) to that block of memory. When you call my_dog.bark(), the system follows the pointer to find the object's data, then calls the bark method with this pointing to that memory.
This is the pointer concept (which gets a module of its own later) dressed up. Object references are pointers wearing nicer syntax.
Here's the same Dog the way a C-like language with 8-byte pointers would lay it out. Strings are usually too big and too variable to live inside the object, so name and breed hold the addresses of their text, stored somewhere else. Every field sits at a fixed offset, so my_dog.age compiles to "the address in my_dog, plus 16". Make a second Dog and it gets its own 24-byte block with its own copies of all three fields.
One Dog object
| Offset | Field | Size | Notes |
|---|---|---|---|
| 0x0 (0) | char* name | 8 | Address of "Rex" |
| 0x8 (8) | char* breed | 8 | Address of "Labrador" |
| 0x10 (16) | int age | 4 | 3, stored right here |
| 0x14 (20) | padding | 4 |
sizeof = 24 bytes, 4 of them padding; alignment 8.
Classes as Custom Types
A class is, in essence, a way to mint your own data type. The language hands you integers and strings out of the box; classes let you define types meaningful to your specific problem — User, Invoice, GameCharacter, NetworkConnection.
Once defined, your class type works anywhere a type is allowed: variable declarations, function parameters, return types, or elements in a collection.
function oldest_dog(dogs) { result = dogs[0] for dog in dogs { if dog.age > result.age { result = dog } } return result}This function works with Dog objects as naturally as another function would work with integers. The ability to define your own types and operations is one of OOP's most powerful features.
From Hardware to Objects
At the machine level, an object is a chunk of memory holding fields laid out sequentially. Accessing dog.name becomes a memory read at the object's base address plus the offset of the name field. Methods are functions that receive a hidden pointer to the object (commonly called this or self) as their first argument. No magic involved. OOP is an abstraction layer sitting on top of the same memory and function calls you've been studying all course. Holding that mapping in your head helps you reason about performance and trace bugs that come down to how objects sit in memory.