Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Classes and records

By the end of this chapter, you'll be able to

  • Define a class with private attributes, a constructor and methods
  • Create objects with new and call their methods
  • Override toString to display an object readably
  • Use a record for a simple, unmodifiable piece of data

A class, some objects

A class is a blueprint that describes attributes (the data) and methods (the actions). An object, or instance, is built from that blueprint with new.

class LoyaltyCard {
    private final String owner;
    private int points;

    LoyaltyCard(String owner) {
        this.owner = owner;
        this.points = 0;
    }

    void recordPurchase(double amount) {
        if (amount > 0) {
            points += (int) (amount / 10);         // 1 point per 10 spent
        }
    }

    boolean redeem(int requested) {
        if (requested <= 0 || requested > points) {
            return false;                          // the rule is protected
        }
        points -= requested;
        return true;
    }

    int getPoints() {
        return points;
    }

    @Override
    public String toString() {
        return owner + ": " + points + " points";
    }
}

void main() {
    var card = new LoyaltyCard("Malik");
    card.recordPurchase(87.5);
    card.recordPurchase(42);
    IO.println(card);
    IO.println("Redeem 50 points: " + card.redeem(50));
    IO.println("Redeem 10 points: " + card.redeem(10));
    IO.println("Left: " + card.getPoints());
}
Malik: 12 points
Redeem 50 points: false
Redeem 10 points: true
Left: 2

Let's break it down:

  • private reserves an attribute for the class's methods. The rest of the program goes through the methods, which apply the rules. This is encapsulation.
  • final on owner: once set by the constructor, it no longer changes.
  • The constructor has the class's name and no return type. It's called by new and initialises the object. this.owner refers to the object's attribute, to tell it apart from the parameter with the same name.
  • getPoints() is a getter: it lets you read a value without being able to change it.
  • toString() describes the object as text. Java calls it automatically when you display the object. @Override signals that we override an existing method, inherited from the Object class that every class descends from. The compiler then checks that it really exists.

10 points are redeemed: 2 are left. No other part of the program could change points.

Step 6 of 6
Text description of the animation
  1. We create a card, then only touch it through its methods.
  2. new calls the constructor: owner is set, points is 0.
  3. 8 full blocks of 10: 8 points.
  4. 4 more points: 12.
  5. redeem refuses: not enough points. The balance doesn't move.
  6. 10 points are redeemed: 2 are left. No other part of the program could change points.

Records: very simple data

Many objects are just bundles of values with no complex rule: a product (name, price), a point (x, y), an appointment date. For these, Java offers records:

record Product(String name, double price) {
    Product {
        if (price < 0) {
            throw new IllegalArgumentException("Negative price: " + price);
        }
    }

    double priceWithTax(double rate) {
        return price * (1 + rate);
    }
}

void main() {
    var tea = new Product("Green tea", 4.0);
    IO.println(tea);
    IO.println(tea.name() + " costs " + tea.price());
    IO.println("With tax: " + tea.priceWithTax(0.25));
    IO.println(tea.equals(new Product("Green tea", 4.0)));
}
Product[name=Green tea, price=4.0]
Green tea costs 4.0
With tax: 5.0
true

In one line, record Product(String name, double price) creates a class with two private final attributes, a constructor, the accessors name() and price(), a readable toString and an equals that compares the values. A record is unmodifiable: to change the price, you create a new Product. The block Product { … } is a compact constructor: it checks the values before creation. We'll see throw in the next chapter.

Your turn

Worked exercise

Worked exercise: the kitchen timer

Write a class Timer with a private attribute seconds. The constructor receives a duration in minutes (negative → 0). Add a method void elapse(int s), which removes seconds without ever going below 0, a method boolean isDone() and a toString in the format mm:ss. With a 3-minute timer, after 75 then 200 seconds, the program must display 03:00, 01:45, then 00:00 done: true.

Hint 1
Math.max(0, seconds - s) stops it going below 0.
Hint 2
String.format("%02d:%02d", seconds / 60, seconds % 60) displays the minutes and seconds on two digits.
Show the solution and common mistakes
class Timer {
    private int seconds;

    Timer(int minutes) {
        this.seconds = Math.max(0, minutes) * 60;
    }

    void elapse(int s) {
        seconds = Math.max(0, seconds - s);
    }

    boolean isDone() {
        return seconds == 0;
    }

    @Override
    public String toString() {
        return String.format("%02d:%02d", seconds / 60, seconds % 60);
    }
}

void main() {
    var t = new Timer(3);
    IO.println(t);
    t.elapse(75);
    IO.println(t);
    t.elapse(200);
    IO.println(t + " done: " + t.isDone());
}
03:00
01:45
00:00 done: true

Common mistakes:

  • Forgetting @Override and writing tostring(): with no compilation error, Java would display Timer@5ca881b5. With @Override, the typo is reported straight away.
  • Making seconds public "to keep it simple": any code could then make it negative.

Summary

  1. 1A class describes attributes and methods; new creates an object by calling the constructor.
  2. 2private attributes are only changed by the methods, which apply the rules.
  3. 3toString, marked @Override, describes the object when it's displayed.
  4. 4A record creates in one line an unmodifiable data class, with accessors, equals and toString.
  5. 5Write each class as if it were in its own file.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.