Classes and objects
What a class, an object, a constructor and this really are, plus references, enums and interfaces, with complete Java and Python code and the traps that bite beginners.
On this page
The problem: data with no home
A coffee shop app starts as a few loose variables. Every drink is a name, a size and a number of espresso shots, kept in three parallel lists, and the price rule lives in a function somewhere else:
names = ["latte", "espresso"]
sizes = ["large", "small"]
shots = [1, 1]
def price(i): # i is a position in all three lists
base = {"small": 300, "medium": 350, "large": 400}[sizes[i]]
return base + 60 * (shots[i] - 1)
This breaks in quiet ways. Delete a drink from names but forget shots, and every later drink gets the wrong number of shots. Anyone can write shots[0] = -3 or sizes[1] = "huge". And the rule "a drink has at least one shot" lives nowhere, so nothing enforces it.
The data and the rules that belong to it are scattered. A class gives them one home.
The idea: a blueprint and the things built from it
A class is a blueprint: it lists the data each thing has (its fields) and what each thing can do (its methods). An object, also called an instance, is one thing built from that blueprint while the program runs. One class, as many objects as you need.
One blueprint, many objects
- A class is a blueprint. It describes what something has and what it can do, but it isn’t the thing itself. Think of a cookie cutter: one cutter, as many cookies as you like.
Three words come up constantly:
| Term | Meaning | Coffee example |
|---|---|---|
| Field (attribute) | A piece of data each object carries | name, size, shots |
| Method | A function that belongs to the class and works on one object's fields | addShot(), priceInCents() |
| Constructor | Special code that runs once when an object is created, to set its starting values and check they make sense | new Coffee("latte", Size.LARGE) |
How it works: new, constructors, state and this
Each time you write new in Java (or call the class like a function in Python), the runtime allocates a fresh object and runs the constructor on it. Every object keeps its own copy of the fields, which is called its state: changing one object leaves the others alone.
Each new object gets its own state
- Each time you write new, you get a brand-new object, also called an instance. The constructor runs once to set its starting values.
- Every object keeps its own state, its own copy of the fields. Eat cookie a twice, and only a loses bites. Cookie b is untouched.
Inside a method, this in Java (self in Python) means "the object this method was called on". There is only one copy of the eat() code, but when you call a.eat() it works on a's fields, and b.eat() works on b's. Python makes this explicit: a.eat() is really Cookie.eat(a).
this is whichever object the method was called on
- Inside a method, this means “the object the method was called on”. When you call a.eat(), this is a; for b.eat(), it’s b. That’s how one method works for every object.
Variables hold references, not objects
This is the single most common beginner surprise. A variable of a class type does not contain the object; it holds a reference, an arrow to where the object lives in memory. Assigning one variable to another copies the arrow.
Two names for one object, and two objects with the same values
So == in Java (and is in Python) asks "same object?", while equals() (Python ==, which calls __eq__) asks "same value?", and only if the class defines what "same value" means. Java strings, records and Python dataclasses define it for you. Your own plain classes do not: by default equals falls back to "same object".
The complete example
Here is the coffee shop rebuilt with every core idea in one place: an enum for the fixed set of sizes, an interface for "anything with a price", a class with a validating constructor, a static (class-level) counter, and a driver.
An enum is a type with a fixed, named set of values. Use one whenever a field can only be one of a few known options (sizes, vehicle types, order statuses): the compiler then rejects "huge", and each constant can carry its own data. An interface is a promise of methods with no implementation; any class that implements it can be used wherever the interface is expected (the interfaces and polymorphism lesson goes deeper).
import java.util.List;
import java.util.Objects;
enum Size {
SMALL(250, 300), MEDIUM(350, 350), LARGE(450, 400);
private final int ml;
private final int baseCents;
Size(int ml, int baseCents) { this.ml = ml; this.baseCents = baseCents; }
int ml() { return ml; }
int baseCents() { return baseCents; }
}
interface Priced {
long priceInCents();
}
class Coffee implements Priced {
private static int created = 0; // static: one counter for the whole class
private final String name; // instance fields: one copy per object
private final Size size;
private int shots;
Coffee(String name, Size size) { // overloaded constructor...
this(name, size, 1); // ...delegates to the full one
}
Coffee(String name, Size size, int shots) {
if (shots < 1) throw new IllegalArgumentException("a coffee needs at least one shot");
this.name = Objects.requireNonNull(name);
this.size = Objects.requireNonNull(size);
this.shots = shots;
created++;
}
void addShot() { this.shots++; }
@Override
public long priceInCents() {
return size.baseCents() + 60L * (shots - 1);
}
static int created() { return created; }
@Override
public String toString() { return size + " " + name + " x" + shots; }
}
public class Main {
public static void main(String[] args) {
Coffee a = new Coffee("latte", Size.LARGE);
Coffee b = new Coffee("latte", Size.LARGE);
a.addShot(); // only a changes
System.out.println(a + " = " + a.priceInCents()); // LARGE latte x2 = 460
System.out.println(b + " = " + b.priceInCents()); // LARGE latte x1 = 400
System.out.println(a == b); // false: two objects
List<Priced> bill = List.of(a, b, new Coffee("espresso", Size.SMALL));
long total = 0;
for (Priced p : bill) total += p.priceInCents();
System.out.println("total = " + total); // total = 1160
System.out.println("coffees made = " + Coffee.created()); // 3
}
}from abc import ABC, abstractmethod
from enum import Enum
class Size(Enum):
SMALL = (250, 300)
MEDIUM = (350, 350)
LARGE = (450, 400)
def __init__(self, ml, base_cents):
self.ml = ml
self.base_cents = base_cents
class Priced(ABC):
@abstractmethod
def price_in_cents(self) -> int: ...
class Coffee(Priced):
created = 0 # class attribute: one counter for the class
def __init__(self, name: str, size: Size, shots: int = 1):
if shots < 1:
raise ValueError("a coffee needs at least one shot")
self.name = name # instance attributes: one copy per object
self.size = size
self.shots = shots
Coffee.created += 1 # not self.created += 1 (see below)
def add_shot(self):
self.shots += 1
def price_in_cents(self) -> int:
return self.size.base_cents + 60 * (self.shots - 1)
def __repr__(self):
return f"{self.size.name} {self.name} x{self.shots}"
if __name__ == "__main__":
a = Coffee("latte", Size.LARGE)
b = Coffee("latte", Size.LARGE)
a.add_shot() # only a changes
print(a, "=", a.price_in_cents()) # LARGE latte x2 = 460
print(b, "=", b.price_in_cents()) # LARGE latte x1 = 400
print(a is b) # False: two objects
bill: list[Priced] = [a, b, Coffee("espresso", Size.SMALL)]
print("total =", sum(p.price_in_cents() for p in bill)) # total = 1160
print("coffees made =", Coffee.created) # 3A few details worth noticing:
- The constructor guards the rules. No
Coffeecan ever exist with zero shots, because the only way to make one runs the check. The encapsulation lesson builds on this. - Static vs instance.
shotsbelongs to each object;createdbelongs to the class itself and is shared. Call static methods on the class (Coffee.created()), not on an object. - Python has no
newand no overloading. CallingCoffee(...)creates the object and runs__init__on it; default arguments (shots=1) replace Java's second constructor. this(...)chains constructors in Java so the validation is written once.
Comparing by value: records and dataclasses
When an object is just a value (an amount of money, a coordinate), you want equals to compare contents. Writing equals and hashCode by hand is easy to get wrong, so let the language do it:
record Money(long cents, String currency) { }
Money x = new Money(500, "EUR");
Money y = new Money(500, "EUR");
System.out.println(x == y); // false: two objects
System.out.println(x.equals(y)); // true: records compare all fieldsfrom dataclasses import dataclass
@dataclass(frozen=True)
class Money:
cents: int
currency: str
x, y = Money(500, "EUR"), Money(500, "EUR")
print(x is y) # False: two objects
print(x == y) # True: dataclasses compare all fieldsRecords and frozen dataclasses are also immutable (their fields cannot be reassigned), which is exactly what you want for values used as map keys.
Options: which kind of type to use
| Kind | Good at | Weak at | Use when |
|---|---|---|---|
| Class | Data plus behaviour plus rules (invariants) | Ceremony if there is no behaviour | The thing has state that changes and rules to protect |
| Record / dataclass | Values: free equals, hashCode, toString, immutability | Rich behaviour, hidden state | Money, coordinates, DTOs, map keys |
| Enum | A fixed, known set of options, each with its own data | Sets that grow at run time (users, products) | Sizes, statuses, vehicle types, directions |
| Interface | A promise that many unrelated classes can keep | Sharing state or code (mostly) | Something that varies: payment methods, pricing rules |
When not to reach for a class
- A pure calculation with no state is a function.
vat(amount)does not need aVatCalculatorobject, especially in Python. - Data that only travels (an API response) is a record or dataclass, not a class with hand-written getters.
- Don't model every noun. In an interview, "Customer address" is often a field, not a class. A class earns its place when it has behaviour or rules of its own.
In the interview
A library has books (title, author, ISBN) and owns several physical copies of each. A copy can be on the shelf or borrowed. Sketch the classes, the enum and the constructors, in Java and Python.
Compare with our answer
enum CopyStatus { ON_SHELF, BORROWED, LOST }
record Book(String isbn, String title, String author) { } // a value: same ISBN, same book
class BookCopy {
private final String barcode;
private final Book book; // many copies share one Book
private CopyStatus status = CopyStatus.ON_SHELF;
BookCopy(String barcode, Book book) {
if (barcode == null || barcode.isBlank()) throw new IllegalArgumentException("barcode required");
this.barcode = barcode;
this.book = java.util.Objects.requireNonNull(book);
}
void borrow() {
if (status != CopyStatus.ON_SHELF) throw new IllegalStateException("not available");
status = CopyStatus.BORROWED;
}
void giveBack() { status = CopyStatus.ON_SHELF; }
CopyStatus status() { return status; }
}from dataclasses import dataclass
from enum import Enum
class CopyStatus(Enum):
ON_SHELF = "on_shelf"
BORROWED = "borrowed"
LOST = "lost"
@dataclass(frozen=True)
class Book: # a value: same ISBN, same book
isbn: str
title: str
author: str
class BookCopy:
def __init__(self, barcode: str, book: Book):
if not barcode:
raise ValueError("barcode required")
self.barcode = barcode
self.book = book # many copies share one Book
self.status = CopyStatus.ON_SHELF
def borrow(self):
if self.status is not CopyStatus.ON_SHELF:
raise RuntimeError("not available")
self.status = CopyStatus.BORROWED
def give_back(self):
self.status = CopyStatus.ON_SHELFA strong answer mentions: Book and BookCopy as separate classes (type versus item) · an enum for the copy status · the copy holding a reference to a shared Book · a constructor that rejects a missing barcode · borrow() refusing a copy that is not on the shelf.
Every customer's cart seems to contain everyone else's items. Find the bug and fix it in both languages.
class Cart:
items = []
def add(self, item):
self.items.append(item)Compare with our answer
items = [] is a class attribute: one list shared by every Cart. self.items.append finds that shared list and mutates it. The Java equivalent is a static list.
import java.util.ArrayList;
import java.util.List;
class Cart {
private final List<String> items = new ArrayList<>(); // no static: one list per cart
void add(String item) { items.add(item); }
List<String> items() { return List.copyOf(items); }
}class Cart:
def __init__(self):
self.items = [] # created per object
def add(self, item):
self.items.append(item)A strong answer mentions: class attribute versus instance attribute · that every Cart reads the same list object · moving the list into __init__ · the Java equivalent being a static field · not using items=[] as a default argument either.
- Class = blueprint (fields + methods). Object = one instance made at run time, with its own state.
- Constructor runs once per object: set starting values and reject invalid ones.
- this / self = the object the method was called on.
- Variables hold references.
b = acopies the arrow, not the object (aliasing). ==/is= same object;equals/ Python=== same value, only if the class defines it.- static / class attribute = shared by all objects; mutable shared state is a bug magnet.
- Enum for fixed option sets; record / dataclass for values; interface for what varies.
- Interview: nouns → classes, verbs → methods; separate the type (
Book) from the item (BookCopy).
1. A ride-hailing app models a ride's status as a String field that can be "requested", "ongoing" or "completed". A bug sets it to "competed". What is the best fix?
An enum makes invalid values impossible to write, so the typo becomes a compile error. Int constants still accept any int; a subclass per status is far heavier and an object cannot change its class.
2. In Java, Coffee a = new Coffee("latte", Size.LARGE); Coffee c = a; c.addShot();. What does a.priceInCents() return if a large latte with one shot costs 400 and each extra shot adds 60?
Assignment copies the reference, not the object. Both names point at one coffee, so a change through c is visible through a.
3. Two Point objects are built with the same x and y. In Java, p1 == p2 is false and p1.equals(p2) is also false. Why?
Object's default equals is identity, the same as ==. Override equals and hashCode, or declare Point as a record, to compare values.
4. A Python class has count = 0 at class level and a method that runs self.count += 1. After calling it on two objects, MyClass.count is still 0. Why?
self.count += 1 reads count through the class, then assigns self.count, which creates an attribute on the instance. Write MyClass.count += 1 (or use a @classmethod).
5. A parking lot design has Vehicle, ParkingSpot and ParkingLot. Where should the rule "a lot's capacity must be positive" be enforced?
A constructor that rejects bad input guarantees every object starts valid. Checks elsewhere can be skipped or forgotten, and a separate validator relies on callers remembering it.
6. Which of these is the best candidate for a record (Java) or frozen dataclass (Python) rather than a regular class?
Records suit immutable values compared by content, which is what a map key needs. The others have state that changes and rules about how it changes, which is a regular class's job.
Score 60% or more and the lesson is marked complete.