typestar

Classes & fields in Java

State made private, behavior made public.

var book = new Book("Dune", 412);
book.addPages(20);
System.out.println(book.describe());

class Book {
    private final String title;
    private int pages;

    Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    void addPages(int more) { pages += more; }

    String describe() { return title + ", " + pages + " pages"; }
}

How it works

  1. private final fields set once in the constructor.
  2. this.title = title tells the parameter and field apart.
  3. Methods like addPages are the only door to the state.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
334
Tokens
100
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 4 in Classes & records, step 18 of 29 in Language basics.

← Previous Next →