Core Java Fundamentals ยท Object-Oriented Programming

Constructors and this()

Constructors set up a new object. Overload them, and let one call another with this(...) to avoid repeating code.

ConstructorsDemo.java

class Book {
    String title;
    int pages;

    Book(String title) {
        this(title, 100);
    }

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

public class ConstructorsDemo {
    public static void main(String[] args) {
        Book a = new Book("Java Basics", 250);
        Book b = new Book("Notes");
        System.out.println(a.title + " " + a.pages + ", " + b.title + " " + b.pages);
    }
}

Step by step

  1. new Book("Java Basics", 250): Java picks the two-argument constructor.
  2. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  3. this.title is the field; plain title is the parameter. this. tells them apart.
  4. pages in the Book object changes from 0 to 250.
  5. Book() has finished, so its variables are gone.
  6. new Book("Java Basics", 250): Java picks the two-argument constructor.
  7. new Book("Notes"): only a title, so the one-argument constructor runs.
  8. this(title, 100) hands the work to the other constructor, with a default of 100 pages.
  9. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  10. title in the Book object changes from null to "Notes".
  11. pages in the Book object changes from 0 to 100.
  12. pages goes out of scope and disappears.
  13. Book() has finished, so its variables are gone.
  14. new Book("Notes"): only a title, so the one-argument constructor runs.
  15. It prints Java Basics 250, Notes 100.
  16. Two books, set up by the same code: "Notes" got the default 100 pages through this(...).