EMZETT.
Login

Classes

In short: A class is a blueprint that describes which properties (fields) and abilities (methods) objects created from it have.

In more detail: A class itself isn’t yet a concrete thing, just the template — only once an object is created with it (instantiated) does a concrete instance with its own values exist. Constructors determine how a new object is initialized when created. Classes can also inherit from other classes (see Inheritance), to reuse shared functionality.

In Depth

The analogy that helps most often: a class is like a blueprint for a house, an object is a specific house built from that plan. Any number of houses can be built from the same blueprint, each with its own address, its own wall colour, etc. — but all with the same basic structure (number of rooms, floor plan).

class Car {
    brand
    speed = 0
 
    accelerate(amount) {
        speed = speed + amount
    }
}
 
car1 = new Car()   // its own object, its own speed value
car2 = new Car()   // completely independent of car1
car1.accelerate(20)  // only affects car1.speed, not car2.speed

A class typically consists of two kinds of members: fields (also called attributes/properties — the data every object individually carries) and methods (the abilities/behaviour that operates on this data). In most languages, a further distinction can also be made between instance members (belong to a specific object, every object has its own copy) and static/class members (belong to the class itself, shared by all objects together).

A good class should, following the “single responsibility” principle, represent as precisely as possible EXACTLY ONE clearly defined task/responsibility — a class that simultaneously handles database access, business logic, and formatting for display quickly becomes cluttered and hard to change without accidentally breaking something else.

See also: Objects, Constructors, Inheritance, OOP