Object-oriented basics · Chapter 1

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.

BeginnerInterview priority: Medium45 min
On this page
  1. The problem: data with no home
  2. The idea: a blueprint and the things built from it
  3. How it works: new, constructors, state and this
  4. The complete example
  5. Options: which kind of type to use
  6. When not to reach for a class
  7. In the interview
  8. Quiz

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

  1. 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:

TermMeaningCoffee example
Field (attribute)A piece of data each object carriesname, size, shots
MethodA function that belongs to the class and works on one object's fieldsaddShot(), priceInCents()
ConstructorSpecial code that runs once when an object is created, to set its starting values and check they make sensenew 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

  1. Each time you write new, you get a brand-new object, also called an instance. The constructor runs once to set its starting values.
  2. 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

  1. 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
    }
}

A few details worth noticing:

  • The constructor guards the rules. No Coffee can ever exist with zero shots, because the only way to make one runs the check. The encapsulation lesson builds on this.
  • Static vs instance. shots belongs to each object; created belongs to the class itself and is shared. Call static methods on the class (Coffee.created()), not on an object.
  • Python has no new and no overloading. Calling Coffee(...) 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 fields

Records 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

KindGood atWeak atUse when
ClassData plus behaviour plus rules (invariants)Ceremony if there is no behaviourThe thing has state that changes and rules to protect
Record / dataclassValues: free equals, hashCode, toString, immutabilityRich behaviour, hidden stateMoney, coordinates, DTOs, map keys
EnumA fixed, known set of options, each with its own dataSets that grow at run time (users, products)Sizes, statuses, vehicle types, directions
InterfaceA promise that many unrelated classes can keepSharing 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 a VatCalculator object, 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

Your turn: a library

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; }
}

A 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.

Your turn: spot the bug

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); }
}

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.

Classes and objects on one page
  • 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 = a copies 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).
Interactive labPractise it: bake objects from a classOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

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?

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?

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?

5. A parking lot design has Vehicle, ParkingSpot and ParkingLot. Where should the rule "a lot's capacity must be positive" be enforced?

6. Which of these is the best candidate for a record (Java) or frozen dataclass (Python) rather than a regular class?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.