Classes and Objects
A class is a blueprint that bundles data with the operations on it; an object is one instance with its own state.
Level: beginner
What is it?
A class defines a type: the fields (state) each instance holds and the methods (behavior) that work on that state. An object is an instance created from the class by a constructor. Methods receive the object they were called on (self in Python, this in Java and JavaScript), which is how one definition works for many instances.
Why does it matter?
Objects let you model a problem in its own vocabulary — Account, Order, Packet — and keep each noun's data and rules together. It is how most large programs in Java, C#, Python, and TypeScript are organized.
Mental model
A cookie cutter and cookies. The class is the cutter: it fixes the shape. Each object is a cookie: same shape, but its own dough, its own bite marks. Changing one cookie does not change the others.
How it works
- Fields hold state; methods define behavior; the constructor sets up a valid initial state.
- Each object has its own copy of instance fields. Class-level (static) fields are shared by all instances.
- Objects are usually references to heap memory, so assigning one variable to another shares the same object.
- Value objects (Money, Point) are compared by content; entities (Account, User) have identity that outlives changes to their fields.
- Prefer small classes with one clear job. A class named Manager or Helper is often a sign it has several.
Steps
- Define the class
- Call the constructor
- Object is created with its own fields
- Call methods on it
- Object is freed when unreachable
Code example: State plus behavior in one place
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
acct = Account("Ada")
acct.deposit(50)
print(acct.owner, acct.balance) # Ada 50Real-world usage
- Domain models: users, orders, invoices, and packets
- GUI widgets and game entities
- Any framework that expects you to subclass or implement a type
Common mistakes
- Creating an object in an invalid state and relying on callers to fix it up.
- Building 'god classes' that know about everything.
- Treating classes as bags of public fields with no behavior.
Interview questions
What is the difference between a class and an object?
A class is the definition — the fields and methods. An object is a specific instance created from it, with its own field values.
What does a constructor do?
It runs when an object is created and establishes a valid initial state: setting fields, validating arguments, and acquiring resources.
What is the difference between an instance method and a static method?
An instance method operates on a particular object and can read its fields. A static method belongs to the class itself and has no instance to work with.