How do I set initial object values using a constructor in Java?

A constructor initializes an object when you create it using the new keyword. You can pass values to the constructor to set the object’s initial state.

In this example, you will create a Book class with a constructor that accepts a title and an author.

Source code

public class ConstructorExample {
    void main() {
        Book firstBook = new Book("Learning Java", "Alice");
        Book secondBook = new Book("Exploring Java", "Bob");

        firstBook.printDetails();
        IO.println();
        secondBook.printDetails();
    }
}

class Book {
    private final String title;
    private final String author;

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

    void printDetails() {
        IO.println("Title: " + title);
        IO.println("Author: " + author);
    }
}

Explanation

The Book class declares two fields:

private final String title;
private final String author;

The private modifier limits direct access to these fields to the Book class. The final modifier means each field can be assigned only once.

The constructor receives the initial field values:

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

A constructor has the same name as its class and does not declare a return type, not even void.

Here, the parameter names match the field names. The keyword this refers to the current object, so this.title identifies the field while title identifies the parameter.

For example:

this.title = title;

This statement assigns the value of the title parameter to the current object’s title field.

The following expression creates a book and passes two arguments to its constructor:

new Book("Learning Java", "Alice")

The constructor sets the new object’s title to "Learning Java" and its author to "Alice".

Each call to new Book(...) creates a separate object with its own field values.

Run the example

Compile and run the file:

javac ConstructorExample.java
java ConstructorExample

Output

Title: Learning Java
Author: Alice

Title: Exploring Java
Author: Bob

What happens to the default constructor?

Java provides a default constructor only when a class declares no constructors.

Since this Book class declares a constructor with two parameters, the following expression causes a compilation error:

new Book()

To create a Book, supply the title and author, or explicitly add a constructor with no parameters.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.