Core Java Fundamentals ยท Object-Oriented Programming
Constructors set up a new object. Overload them, and let one call another with this(...) to avoid repeating code.
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);
}
}Object) runs first.this.title is the field; plain title is the parameter. this. tells them apart.pages in the Book object changes from 0 to 250.Book() has finished, so its variables are gone.this(title, 100) hands the work to the other constructor, with a default of 100 pages.Object) runs first.title in the Book object changes from null to "Notes".pages in the Book object changes from 0 to 100.pages goes out of scope and disappears.Book() has finished, so its variables are gone.Java Basics 250, Notes 100.