java · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A list of planets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
static class Planet {
private String name;
private int moons;
Planet(String name, int moons) {
this.name = name;
this.moons = moons;
}
public String toString() {
return name + " (" + moons + ")";
}
}
public static void main(String[] args) {
ArrayList<Planet> planets = new ArrayList<>();
planets.add(new Planet("Earth", 1));
planets.add(new Planet("Mars", 2));
System.out.println(planets);
}
}
your turn
Your turn. Describe a pizza.
Finish the return on line 10 so a pizza describes itself using both of its fields. Then press run.
output
press run to see what happens
fix it
The dog will not describe itself. Fix it!
output
press run to see what happens
- Java says
toString() in Dog cannot override toString() in Objecton line 7. - The free
toStringis open to code anywhere, so yours must be too. One word is missing. - Put
publicin front ofString toString()on line 7, then press run.
nailed it
your objects introduce themselves. :D
- Java calls
toStringwhenever it needs an object as text. - Write
public String toString()to choose that text. - Lists print each item using its own
toString.
new words in your collection
- toString
- public
This lesson isn’t saved. A free account remembers every lesson you finish.