GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java9 / 25

Classes and Objects

Bringing together state, behavior, and invariants

8.1 Learning objectives

By the end of this chapter, you should be able to:

  • distinguish between class, object, field, and method;
  • initialize objects with constructors;
  • use this to distinguish a field from a parameter;
  • protect internal state with private;
  • express rules through domain operations rather than generic setters.

8.2 State and behavior

The class defines; each object maintains its own state.

Figure 8.1. The class defines; each object maintains its own state.

A class defines structure and available operations. An object is a concrete instance of that class. Its fields form its state; its methods define its behavior.

class PointsAccount {
    private int balance;

    public PointsAccount(int initialBalance) {
        if (initialBalance < 0) {
            throw new IllegalArgumentException("Invalid initial balance.");
        }
        this.balance = initialBalance;
    }

    public void credit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Credit amount must be positive.");
        }
        balance += amount;
    }

    public boolean debit(int amount) {
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }

    public int getBalance() {
        return balance;
    }
}

Checking amount <= 0 is essential: without it, subtracting a negative number would increase the balance. The private field can only change through operations that preserve the rules.

8.3 Constructors and this

Comic: a class is not an object.

Figure 8.2. Comic: a class is not an object.

A constructor establishes a valid initial state. this.name refers to the current object’s field, while name refers to the parameter:

class Chatbot {
    private final String name;

    public Chatbot(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name is required.");
        }
        this.name = name.strip();
    }
}

final prevents the reference from being reassigned after construction.

8.4 The chatbot class

import java.util.ArrayList;
import java.util.List;

class BasicChatbot {
    private final String name;
    private final List<String> history = new ArrayList<>();

    BasicChatbot(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name is required.");
        }
        this.name = name.strip();
    }

    String respond(String message) {
        if (message == null || message.isBlank()) {
            return "Enter a message.";
        }
        history.add(message.strip());
        return name + ": I received your message.";
    }

    List<String> viewHistory() {
        return List.copyOf(history);
    }
}

public class Chapter08Classes {
    public static void main(String[] args) {
        BasicChatbot bot = new BasicChatbot("TutorJavaBot");
        System.out.println(bot.respond("hi"));
        System.out.println(bot.viewHistory());
    }
}

The copy returned by viewHistory prevents external modification of the internal list.

8.5 Initial composition

Composition models a “has-a” relationship. A chatbot can have an object responsible for its history; a classroom can have a list of students. When a responsibility grows, moving history into its own class prevents the chatbot from taking on too much work.

8.6 Project evolution: version 8

Turn standalone variables and methods into a BasicChatbot object. main creates the object and coordinates input and output; the class protects its name, history, and response rules.

The complete example is in examples/src/Chapter08Classes.java.

8.7 Verifiable practice

  1. Add a totalMessages() method.
  2. Reject blank names in the constructor.
  3. Confirm that the returned list cannot mutate the internal history.
  4. Explain which invariant each validation protects.

Invariant

An invariant is a condition that must remain true throughout an object’s entire lifetime, such as “the chatbot’s name is never blank.”