A constructor looks like a method, but it has the same name as the class, and no return type. Its parameters bring in the starting values. Inside, it copies them into the fields. It runs automatically, whenever you write new Book.
Main.javajava
public class Book { String title; String author; int pages; Book(String t, String a, int p) { title = t; author = a; pages = p; }}
Now new Book takes three arguments. Each book is fully set up, in a single line. Run it. Both books, with their authors.
Main.javajava
public class Main { public static void main(String[] args) { Book a = new Book("Dune", "Frank Herbert", 412); Book b = new Book("Emma", "Jane Austen", 474); System.out.println(a.title + " by " + a.author); System.out.println(b.title + " by " + b.author); }}
Output
Dune by Frank Herbert
Emma by Jane Austen
Also uses Book.java
public class Book { String title; String author; int pages; Book(String t, String a, int p) { title = t; author = a; pages = p; }}
Once you write a constructor, Java no longer gives you the empty one for free. So new Book, with no arguments, fails. Run it. The constructor can't be applied, because it needs three values.
Main.javajava
public class Main { public static void main(String[] args) { Book c = new Book(); }}
Output
Main.java:3: error: constructor Book in class Book cannot be applied to given types;
Book c = new Book();
^
required: String,String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
error: compilation failed
Also uses Book.java
public class Book { String title; String author; int pages; Book(String t, String a, int p) { title = t; author = a; pages = p; }}
Constructors can be overloaded, like methods. One takes a title and pages. The other takes just a title, and uses a hundred pages. Run it. Dune has four hundred and twelve pages, and the short story gets a hundred.
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 t, int p) { title = t; pages = p; } Book(String t) { title = t; pages = 100; }}