JAVA-102 · Lesson 1 of 12 · 24 min

Designing classes and objects

▶ Video coming soon A video version of this lesson is on the way.

JAVA-101 ended with PartsDesk, Hamza Belcourt's console inventory tool for the parts room at Second Gear Cycles, demonstrated to Odile and Kofi on Saturday, November 14, 2026. Kofi plans to try it on the full parts list from December 1. Ingrid Vallancourt, Hamza's mentor, has already said what the winter term is for. PartsDesk works, but it is one long file of static methods and parallel ideas held together by care. The plan for the term, from Wednesday, January 13, 2027, is to learn the object-oriented way of building programs, and to finish in April with a second, larger program: a booking system for the shop's repair jobs and the rental bikes Odile wants to offer from the spring.

This first lesson is about design before code. Lesson 11 of JAVA-101 showed what a class is: a blueprint with fields and methods, from which objects are made. Knowing the syntax is the easy part. The hard part, and the part this lesson practises, is deciding which classes a program needs, what each one is responsible for and how they work together.

Why objects?

A program written only with static methods and arrays keeps data in one place and the code that changes it in another. As the program grows, every method needs to know the layout of every array, and a change to one rule means searching the whole file. Object-oriented programming groups each piece of data with the code that looks after it. A booking knows its own date and status and how to change them; a bike knows its own size and condition. The rest of the program asks objects to do things instead of reaching into their data.

Three ideas carry most of the weight, and this course takes them one at a time. Encapsulation (lesson 2) means an object protects its own data and offers methods instead. Inheritance (lesson 5) lets one class build on another. Polymorphism (lesson 7) lets different kinds of object answer the same request in their own way. Underneath all three is good class design: classes with a clear job, a small set of methods and as little knowledge of each other as possible.

Finding the classes

A dependable starting point is to write down what the program must do in plain sentences and then look at the words. The nouns suggest classes or fields; the verbs suggest methods. Ingrid asked Hamza to describe the booking problem in his own words, and he wrote: "A customer books a repair for their bike on a date. A mechanic does the job, and the shop marks the booking ready. Later, customers will also rent a refurbished bike for a number of days and pay a deposit."

Nouns and verbs in Hamza's description
WordKindLikely becomes
customernouna Customer class
repair, bookingnouna Booking class (repair bookings first)
bikenouna Bike class
datenouna field of Booking
mechanicnouna field, perhaps a name, for now
depositnouna field of a rental booking
books, marks ready, rents, paysverbmethods such as book, markReady, rent

Not every noun deserves a class. "Shop" is the whole program, and "date" is already provided by Java's library as LocalDate, which later courses use. A noun becomes a class when it has several pieces of data of its own and some behaviour; a noun with a single value, such as a mechanic's name for now, can stay a field. The first list is a guess, and good designers expect to revise it.

Responsibilities and CRC cards

For each candidate class, write its responsibilities: what it knows and what it does. A classic low-tech tool is the CRC card, an index card with the class name at the top, its responsibilities on the left and its collaborators, the other classes it works with, on the right. Moving cards around a table makes it obvious when one class is doing too much or when two classes know the same thing.

Three index cards side by side. Customer: knows name, phone, email; collaborates with Booking. Bike: knows make, model, frame size, serial; collaborates with Customer. Booking: knows customer, bike, date, job, status, price; can confirm, mark ready, describe; collaborates with Customer and Bike.
CRC cards for Hamza's first three classes

A useful test is the single responsibility rule of thumb: you should be able to say what a class is for in one sentence without the word "and". "A Booking records one repair appointment and its progress" passes. "A Booking stores the appointment and sends text messages and prints invoices" fails, so the messaging and printing belong elsewhere.

From design to code

Once the cards look right, each one turns into a class. Fields come from the "knows" column, methods from the "does" column. The first version below keeps everything in one file, as in JAVA-101, with the extra classes below Main and without the word public. Lesson 11 moves each class into its own file and package.

Java Example · Main.java
public class Main {
    public static void main(String[] args) {
        Customer ana = new Customer("Ana Ruiz", "905-555-0142");
        Bike bike = new Bike("Raleigh", "Cadent 2", 54);
        Booking b = new Booking(ana, bike, "2027-01-23", "brake bleed");

        System.out.println(b.describe());
        b.confirm();
        System.out.println(b.describe());
    }
}

class Customer {
    String name;
    String phone;

    Customer(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
}

class Bike {
    String make;
    String model;
    int frameCm;

    Bike(String make, String model, int frameCm) {
        this.make = make;
        this.model = model;
        this.frameCm = frameCm;
    }

    String label() {
        return make + " " + model + " (" + frameCm + " cm)";
    }
}

class Booking {
    Customer customer;
    Bike bike;
    String date;
    String job;
    String status = "REQUESTED";

    Booking(Customer customer, Bike bike, String date, String job) {
        this.customer = customer;
        this.bike = bike;
        this.date = date;
        this.job = job;
    }

    void confirm() {
        status = "CONFIRMED";
    }

    String describe() {
        return date + "  " + customer.name + "  " + bike.label() + "  " + job + "  [" + status + "]";
    }
}
Output
2027-01-23  Ana Ruiz  Raleigh Cadent 2 (54 cm)  brake bleed  [REQUESTED]
2027-01-23  Ana Ruiz  Raleigh Cadent 2 (54 cm)  brake bleed  [CONFIRMED]

What this code does

Each CRC card has become a class whose fields are the things the card knows. A Booking holds references to a Customer and a Bike, so describe can ask the bike for its own label instead of building it. Calling confirm changes the state of that one booking object, and describe shows the change.

Look at how Booking uses Bike. It does not read make, model and frameCm and glue them together; it calls bike.label() and lets the bike decide how it is described. That is the habit to build from the first day: ask an object to do something rather than taking its data out and doing it yourself, a guideline often summed up as tell, don't ask.

Objects have state, behaviour and identity

Every object has three properties worth keeping apart. Its state is the current values of its fields: this booking is CONFIRMED for January 23. Its behaviour is what its methods do: confirm, describe. Its identity is the fact that it is one particular object, different from every other even if their fields match. Two bookings for the same customer, bike and date are still two bookings, and cancelling one must not touch the other.

Java Example · Main.java
public class Main {
    public static void main(String[] args) {
        Slot morning = new Slot("2027-01-23", 9);
        Slot sameTime = new Slot("2027-01-23", 9);
        Slot afternoon = new Slot("2027-01-23", 14);

        morning.take();
        System.out.println(morning.describe());
        System.out.println(sameTime.describe());
        System.out.println(afternoon.describe());
        System.out.println("Same object? " + (morning == sameTime));
        System.out.println("Same time? " + morning.sameTimeAs(sameTime));
    }
}

class Slot {
    String date;
    int hour;
    boolean taken;

    Slot(String date, int hour) {
        this.date = date;
        this.hour = hour;
    }

    void take() {
        taken = true;
    }

    boolean sameTimeAs(Slot other) {
        return date.equals(other.date) && hour == other.hour;
    }

    String describe() {
        return date + " " + hour + ":00 " + (taken ? "taken" : "free");
    }
}
Output
2027-01-23 9:00 taken
2027-01-23 9:00 free
2027-01-23 14:00 free
Same object? false
Same time? true

What this code does

morning and sameTime have identical fields but are two separate objects, so taking one leaves the other free. The == test compares identity and is false, while sameTimeAs compares state and is true. Lesson 10 turns this idea into a proper equals method.

The difference between "the same object" and "an object with the same values" matters constantly. Two references to one object share every change; two equal-looking objects do not. When you design a class, decide which question your program will ask about it, and lesson 10 shows how to make Java's own equals answer the second one.

Drawing classes

Designers sketch classes with UML class diagrams, a common notation in which each class is a box with three parts: the name, the fields and the methods. A line between two boxes shows that one class uses or holds the other, and a number near the end of the line, such as 1 or *, says how many. You do not need every detail of UML; a few boxes and arrows are enough to talk a design over before writing it.

A UML class diagram with three boxes. Booking has fields customer, bike, date, job and status, and methods confirm(), markReady() and describe(). Lines run from Booking to Customer (name, phone) and from Booking to Bike (make, model, frameCm, label()). Labels show each booking has exactly one customer and one bike, while a customer can have many bookings.
A first class diagram for the booking system

Methods that keep the rules

A class is not only a bag of fields. It is the natural home for the rules that apply to its data. Odile's rule for repair bookings is that a booking moves forward through REQUESTED, CONFIRMED and READY, and a booking that is already READY cannot go back to CONFIRMED. If every part of the program changed the status field directly, the rule would have to be checked everywhere. Put it in the class instead, and it is checked once.

Java Example · Main.java
public class Main {
    public static void main(String[] args) {
        Booking b = new Booking("Ana Ruiz", "brake bleed");
        System.out.println(b.markReady());
        System.out.println(b.confirm());
        System.out.println(b.markReady());
        System.out.println(b.confirm());
        System.out.println("Final status: " + b.status);
    }
}

class Booking {
    String customer;
    String job;
    String status = "REQUESTED";

    Booking(String customer, String job) {
        this.customer = customer;
        this.job = job;
    }

    String confirm() {
        if (!status.equals("REQUESTED")) {
            return "Cannot confirm: booking is " + status;
        }
        status = "CONFIRMED";
        return "Confirmed " + job + " for " + customer;
    }

    String markReady() {
        if (!status.equals("CONFIRMED")) {
            return "Cannot mark ready: booking is " + status;
        }
        status = "READY";
        return job + " is ready for pickup";
    }
}
Output
Cannot mark ready: booking is REQUESTED
Confirmed brake bleed for Ana Ruiz
brake bleed is ready for pickup
Cannot confirm: booking is READY
Final status: READY

What this code does

confirm and markReady each check the current status before changing it, so the booking can only move forward in the agreed order. Calling markReady too early, or confirm too late, returns a message and leaves the status alone. Lesson 9 replaces the status Strings with an enum, and lesson 8 replaces the messages with exceptions.

There is still a weakness: main could write b.status = "READY" and skip every check. Lesson 2 closes that door with private fields. For now, the point is the design decision: the rules about bookings belong inside Booking.

Cohesion and coupling

Two words describe the quality of a design. Cohesion is how well the parts of a class belong together; a cohesive class does one job and all its fields and methods serve it. Coupling is how much classes depend on each other's details; loosely coupled classes talk through a few methods and can change inside without breaking each other. Aim for high cohesion and low coupling. In the first example, Booking is coupled to Bike only through label(): if Hamza later stores the frame size in inches, Booking does not change.

Design warning signs
SignWhat it suggestsWhat to try
A class with dozens of fieldsIt is doing several jobsSplit it; move groups of fields into their own classes
A method that reads five fields of another objectThe work belongs in the other classMove the method there and call it
The same three fields passed around togetherA missing classMake a small class or record for them
A class named Manager, Helper or Util with many methodsLow cohesionGive each method a home with the data it uses
Changing one class forces edits in many othersHigh couplingHide details behind methods

The design for the term

By the end of the evening on January 13, Hamza and Ingrid plan to agree a first list of classes for the booking system, knowing it will change: Customer, Bike, Booking and a BookingBook that keeps all the bookings and answers questions such as "what is booked on Saturday?". Each later lesson adds a tool that improves the design: private fields and validation, better constructors, shared constants, a rental booking that extends the repair booking, interfaces for things that have a price, exceptions for bad requests, an enum for status, proper equals methods and finally packages.

Java Example · Main.java
public class Main {
    public static void main(String[] args) {
        BookingBook book = new BookingBook(10);
        book.add(new Booking("Ana Ruiz", "2027-01-23", "brake bleed"));
        book.add(new Booking("Theo Park", "2027-01-23", "wheel true"));
        book.add(new Booking("Mei Lin", "2027-01-30", "full tune-up"));

        System.out.println("Bookings on 2027-01-23:");
        for (Booking b : book.on("2027-01-23")) {
            System.out.println("  " + b.describe());
        }
        System.out.println("Total bookings: " + book.size());
    }
}

class Booking {
    String customer;
    String date;
    String job;

    Booking(String customer, String date, String job) {
        this.customer = customer;
        this.date = date;
        this.job = job;
    }

    boolean isOn(String day) {
        return date.equals(day);
    }

    String describe() {
        return customer + ": " + job;
    }
}

class BookingBook {
    Booking[] items;
    int count;

    BookingBook(int capacity) {
        items = new Booking[capacity];
    }

    void add(Booking b) {
        items[count] = b;
        count++;
    }

    int size() {
        return count;
    }

    Booking[] on(String day) {
        int n = 0;
        for (int i = 0; i < count; i++) if (items[i].isOn(day)) n++;
        Booking[] result = new Booking[n];
        int k = 0;
        for (int i = 0; i < count; i++) if (items[i].isOn(day)) result[k++] = items[i];
        return result;
    }
}
Output
Bookings on 2027-01-23:
  Ana Ruiz: brake bleed
  Theo Park: wheel true
Total bookings: 3

What this code does

BookingBook is responsible for keeping bookings and finding them, so main never touches the array inside it. The on method asks each booking whether it is on the given day rather than reading its date field. JAVA-120 replaces the fixed array with a list that grows on its own.

The class that holds many objects and answers questions about them is a common pattern, sometimes called a repository or a registry. Keeping the array inside it means the rest of the program does not care how bookings are stored. When JAVA-120 swaps the array for an ArrayList, only BookingBook changes.

Try it yourself

A Customer that describes itself

Complete the Customer class so it stores a name, a phone and a visits count given to the constructor.

Add a method describe() that returns text such as Ana Ruiz (555-0142), 3 visits, and a method isRegular() that returns true when the customer has 5 or more visits. The program should print two descriptions and Regular: false and Regular: true.

public class Main {
    public static void main(String[] args) {
        Customer a = new Customer("Ana Ruiz", "555-0142", 3);
        Customer b = new Customer("Theo Park", "555-0177", 7);
        System.out.println(a.describe());
        System.out.println(b.describe());
        System.out.println("Regular: " + a.isRegular());
        System.out.println("Regular: " + b.isRegular());
    }
}

class Customer {
    String name;
    String phone;
    int visits;

    Customer(String name, String phone, int visits) {
    }

    String describe() {
        return "";
    }

    boolean isRegular() {
        return false;
    }
}

Try it yourself

Tell, don't ask

The starter program works out a rental price in main by reading the bike's fields. Move that work into the RentalBike class as a method priceFor(int days) that returns the price in dollars: the dailyRate times the number of days, with every seventh day free (so 7 days cost the same as 6).

Change main to call priceFor so it prints City bike, 3 days: 45 dollars and City bike, 7 days: 90 dollars.

public class Main {
    public static void main(String[] args) {
        RentalBike bike = new RentalBike("City bike", 15);
        int days = 3;
        int price = bike.dailyRate * days;
        System.out.println(bike.name + ", " + days + " days: " + price + " dollars");
        days = 7;
        price = bike.dailyRate * days;
        System.out.println(bike.name + ", " + days + " days: " + price + " dollars");
    }
}

class RentalBike {
    String name;
    int dailyRate;

    RentalBike(String name, int dailyRate) {
        this.name = name;
        this.dailyRate = dailyRate;
    }
}

Common mistakes

  • MistakeMaking a class for every noun, including ones with a single value.

    InsteadA noun becomes a class only when it has its own data and behaviour; otherwise it can be a field.

  • MistakeReading several fields of another object to do a job for it.

    InsteadMove the job into that object's class and call the method: tell, don't ask.

  • MistakeA class that "stores bookings and prints invoices and sends texts".

    InsteadGive each responsibility its own class so each one can be described without the word and.

  • MistakeExpecting == to say whether two objects hold the same values.

    Instead== compares identity; write a method such as sameTimeAs, and later equals, to compare state.

  • MistakeLetting every part of the program change a status field directly.

    InsteadPut the rule in a method of the class so it is checked in one place.

Summary and key terms

  • Object-oriented programming groups data with the code that looks after it, so the rest of a program asks objects to do things instead of reaching into their data.
  • Nouns in a problem description suggest classes and fields, verbs suggest methods, and a noun deserves a class only when it has data and behaviour of its own.
  • CRC cards list a class's responsibilities and collaborators and expose classes that do too much.
  • A class should have a single responsibility that can be stated in one sentence.
  • Every object has state, behaviour and identity; == compares identity, not state.
  • UML class diagrams show classes as boxes with name, fields and methods, joined by lines with counts.
  • Rules about an object's data belong in its own methods.
  • Good designs have high cohesion and low coupling, and a repository class can keep many objects and answer questions about them.
Object-oriented programming
A style of programming in which data and the code that works on it are grouped into objects.
Responsibility
Something a class knows or does on behalf of the program.
CRC card
An index card listing a class, its responsibilities and its collaborators.
Collaborator
Another class a class works with to do its job.
Single responsibility
The guideline that a class should have one clear job.
State
The current values of an object's fields.
Identity
The fact that an object is one particular object, distinct from all others.
UML class diagram
A drawing of classes as boxes with their fields, methods and relationships.
Cohesion
How closely the parts of a class belong together.
Coupling
How much classes depend on each other's details.
Tell, don't ask
The guideline of asking an object to do a job instead of taking its data out.
Repository
A class that keeps a collection of objects and answers questions about them.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which words in a problem description suggest classes, and which suggest methods?

    Show answer

    Nouns suggest classes or fields; verbs suggest methods.

  2. When should a noun stay a field instead of becoming a class?

    Show answer

    When it is a single value with no behaviour of its own, such as a mechanic's name for now.

  3. What does a CRC card record?

    Show answer

    A class's name, its responsibilities and the other classes it collaborates with.

  4. Two Slot objects have the same date and hour. Why is morning == sameTime false?

    Show answer

    == compares identity, and they are two different objects.

  5. Why put the status rules inside Booking?

    Show answer

    So they are checked in one place, whatever part of the program changes the booking.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz