It's natural to give parameters the same name as the fields. But then, which title is which? This dot title means the field of this object. Plain title means the parameter. And this, with brackets, calls another constructor, of the same class.
Main.javajava
public class Book { String title; int pages; Book(String title, int pages) { this.title = title; this.pages = pages; } Book(String title) { this(title, 100); }}
The second constructor passes the title on, with a hundred pages. Run it. Both books are set up correctly.
Main.javajava
public class Main { public static void main(String[] args) { Book a = new Book("Dune", 412); Book b = new Book("A Short Story"); System.out.println(a.title + ": " + a.pages); System.out.println(b.title + ": " + b.pages); }}
Output
Dune: 412
A Short Story: 100
Also uses Book.java
public class Book { String title; int pages; Book(String title, int pages) { this.title = title; this.pages = pages; } Book(String title) { this(title, 100); }}
Here we forgot this. Title equals title just copies the parameter into itself. The field never changes. Run it. The title is null! This is a very common bug.
Book.javajava
public class Book { String title; Book(String title) { title = title; } public static void main(String[] args) { Book b = new Book("Dune"); System.out.println("Title: " + b.title); }}
This means the current object. This dot field avoids confusion with parameters. And this, with brackets, calls another constructor. Next, methods that belong to objects.