Java Constructor

Summary: in this tutorial, you will learn how to use Java constructor to create an object and initialize the initial state of the object.

Introduction to the Java constructor

In Java, a constructor is a special method that has the same name as the class and has no return type.

Unlike a regular method that you need to call explicitly, Java invokes the constructor when you create a new object.

Typically, you use the constructor to initialize the initial state of an object.

The following shows the syntax for defining a constructor of a class:

public class MyClass {
    public MyClass() {
       // ...
    }
}Code language: Java (java)

In this syntax, the MyClass() is a constructor of the MyClass class. This constructor has no parameters. It is known as a parameterless constructor.

The following example shows how to define a constructor for the Person class:

class Person {
    public Person() {
        System.out.println("The constructor was called.");
    }
}Code language: Java (java)

When you create a new Person object using the new keyword, the Person() constructor is called automatically:

var person = new Person();Code language: Java (java)

You should see the following message on the screen:

The constructor was called.Code language: Java (java)

Typically, a constructor has parameters that hold the initial state of a new object:

public class MyClass {
    public MyClass(dataType p1, dataType p2, ...) {
    }
}Code language: Java (java)

For example, the following Person class has a constructor that has two parameters name and age:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        setName(name);
        setAge(age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}Code language: Java (java)

In this example, we call the setName() and setAge() methods in the constructor to set the name and age of a Person object.

The following creates a new Person object, initialize its name and age to "John" and 22, and display them on the screen:

var person = new Person("John", 22);

System.out.printf("%s %d",
    person.getName(),
    person.getAge()
);Code language: Java (java)

Output:

John 22Code language: Java (java)

Constructor overloading

Java supports constructor overloading that allows a class to have multiple constructors with different parameter lists. Constructor overloading allows you to create objects with different initializations.

The following Person class has two constructors, one with parameters and the other without any parameters:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        setName(name);
        setAge(age);
    }

    public Person(){
        setName("Anonymous");
        setAge(18);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}Code language: Java (java)

In this example, the Person constructor, which has no parameters, initializes the name to "Anonymous" and age to 22.

If you create a new Person object without passing any parameter, Java will call the parameterless constructor:

var person = new Person();

System.out.printf("%s %d",
    person.getName(),
    person.getAge()
);Code language: Java (java)

Output:

Anonymous 18Code language: Java (java)

But if you create a new Person object and pass the name and age parameters, Java will call the parameterized constructor:

var person = new Person("Jane", 20);

System.out.printf("%s %d",
    person.getName(),
    person.getAge()
);Code language: Java (java)

Output:

Jane 20Code language: Java (java)

Chaining constructors

A constructor can call another constructor, which is known as constructor chaining. This technique helps eliminate duplicate code and enhances code reuse.

To call a constructor, you use Java this keyword and pass arguments if required.

For example, in the parameterless constructor of the Person class, you can call the parameterized constructor as follows:

public Person() {
    this("Anonymous", 18);
}Code language: Java (java)

In this example, the statement this("Anonymous", 18) is a call of the constructor Person(String name, int age) that initializes the name and age fields.

Instead of calling the setName() and setAge() methods, the parameterless constructor calls the parameterized constructor.

Here’s the complete Person class:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        setName(name);
        setAge(age);
    }

    public Person() {
        this("Anonymous", 18);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}Code language: Java (java)

Default constructors

If you don’t explicitly define any constructor for a class, Java will implicitly create a constructor. This constructor is called a default constructor.

The default constructor takes no arguments and initializes the instance fields to their default values.

For example:

class Counter {
    private int current;

    public int getCurrent() {
        return current;
    }
    public void increase(){
        current++;
    }
}Code language: Java (java)

The Counter class has no explicit constructor, therefore, it has an implicit default constructor. Also, the default constructor initializes the instance field e.g., count to 0.

The following program illustrates how to use the Counter class with a default constructor:

public class App {
    public static void main(String[] args) {
        var counter = new Counter();
        System.out.println(counter.getCurrent());
    }
}Code language: Java (java)

Output:

0Code language: Java (java)

How it works.

First, create a new Counter object:

var counter = new Counter();Code language: Java (java)

Java will call the default constructor that initializes the current field to its default value, which is zero.

Second, display the value of the current field by using the getCurrent() method:

System.out.println(counter.getCurrent());Code language: Java (java)

It displays zero as expected.

Summary

  • Java constructor is a special method that has the same name as the class and does not have a return type.
  • Java constructor is invoked automatically during object creation.
  • Use constructors to initialize the initial state of an object.
  • Chain constructors to reuse the code.
  • A default constructor is provided by Java when a class doesn’t explicitly define any constructors. It initializes the object with default values.