×

java · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Write and your objects print nicely.

Print an object and you get something like Main$Book@1b6d3586: its class name and a code. That comes from a plain toString method that every class gets for free. Java calls toString whenever it needs your object as text.

Write your own and you choose the text: . Now printing the book shows Matilda by Roald Dahl, and so does joining it to a string.

It must be public, open to code anywhere, because the free version is public too. Lists print each item with its own toString.

import java.util.*;
public class Main {
    static class Book {
        private String title;
        private String author;
        Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
        public String toString() {
            return title + " by " + author;
        }
    }
    public static void main(String[] args) {
        Book book = new Book("Matilda", "Roald Dahl");
        System.out.println(book);
        System.out.println("Reading: " + book);
        System.out.println(List.of(book, new Book("Holes", "Louis Sachar")));
    }
}

The code after the @ in the free version can change from run to run, so never rely on it.