How to use constructors
Declare a constructor
A constructor has the class name and no return type.
class Book {
String title;
Book(String title) {
this.title = title;
}
}
Call the constructor
Arguments after new must match an available constructor.
Book book = new Book("Java Basics");
System.out.println(book.title);
Use this
this refers to the current object and distinguishes a field from a parameter with the same name.
Book(String title) {
this.title = title;
}
Overload constructors
A class may provide constructors with different parameter lists. One constructor can delegate to another with this(...) as its first statement.
Book() {
this("Untitled");
}