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
private finalfields set once in the constructor.this.title = titletells the parameter and field apart.- Methods like
addPagesare the only door to the state.
Keywords and builtins used here
BookaddPagesclassdescribefinalintnewprivatereturnthisvarvoid
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.
Step 1 of 4 in Classes & records, step 18 of 29 in Language basics.