Skip to content
Classes & Instances
step 1/3

Reading — step 1 of 3

Object-Oriented Programming

~2 min readClosures & Classes

Classes & Instances

Classes are templates for creating objects. They bundle data (fields) and behavior (methods) into a single unit. Adding classes to our language gives users a powerful organizational tool.

Class Declarations

class Dog {
    init(name, breed) {
        this.name = name;
        this.breed = breed;
    }

    bark() {
        print this.name + " says Woof!";
    }
}

A class contains methods — functions bound to the class. The special init method is the constructor, called automatically when creating an instance.

Instances and Properties

var rex = Dog("Rex", "Labrador");
rex.bark();           // "Rex says Woof!"
print rex.name;       // "Rex"
rex.tricks = 3;       // set a new property
print rex.tricks;     // 3

Instances are created by calling the class like a function. Properties can be accessed with dot notation and are stored per-instance. Unlike Java or C++, our language allows adding properties dynamically — like Python and JavaScript.

The this Keyword

Inside a method, this refers to the instance the method was called on. this is implemented as a hidden variable bound in the method's environment:

callMethod(instance, method, args):
    env = new Environment(enclosing=method.closure)
    env.define("this", instance)
    // bind parameters and execute body

Implementation

A class at runtime is an object with:

  • A name
  • A map of methods (name to function)

An instance at runtime is an object with:

  • A reference to its class (for method lookup)
  • A map of fields (name to value)

Property access follows a specific order: first check the instance's fields, then the class's methods. This means a field can shadow a method.

How Python Does It

Python classes are far more dynamic — classes themselves are objects, metaclasses control class creation, and the MRO (Method Resolution Order) handles multiple inheritance. Our system is simpler: single inheritance, no metaclasses, no multiple inheritance. This matches the design in Crafting Interpreters.

Your Task

Implement class declarations, instances, properties (get and set), methods, and the this keyword.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…