Chapter 29 of 57

Constructors in Java

When we create an object, we often need to give it some initial values. For example, when creating a Student object, we may want to immediately set the student's name and age.

We could create the object first and then assign the values separately:

Student student = new Student();

student.name = "John";
student.age = 20;

But Java provides a cleaner way to initialize an object when it is created. This is done using a constructor.

A constructor is a special block of code that is automatically called when we create an object.

Creating a Constructor

A constructor looks similar to a method, but there are a few important differences. Its name must be exactly the same as the class name, and it does not have a return type.

For example:

class Student {
    String name;
    int age;

    Student() {
        System.out.println("Student object created!");
    }
}

Now when we create an object:

Student student = new Student();

the constructor automatically runs.

Output:

Student object created!

Notice that we didn't call Student() ourselves. Java automatically calls the constructor when new Student() is used.

Constructor with Parameters

Constructors become much more useful when we use parameters.

For example:

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Now we can create a student and provide the values immediately:

Student student = new Student("John", 20);

System.out.println(student.name);
System.out.println(student.age);

Output:

John
20

Instead of creating the object and assigning each value separately, the constructor initializes everything when the object is created.

Why Do We Use this?

You may have noticed something interesting:

Student(String name, int age) {
    this.name = name;
    this.age = age;
}

The class already has fields called name and age, and the constructor parameters have the same names.

So Java needs a way to distinguish between them.

this.name refers to the field belonging to the current object, while name refers to the parameter passed to the constructor.

So:

this.name = name;

basically means:

Take the name parameter and store it in this object's name field.

We will explore this in more detail separately.

Default Constructor

If you don't create any constructor yourself, Java automatically provides a default constructor for the class.

For example:

class Student {
    String name;
    int age;
}

We can still write:

Student student = new Student();

and it works.

However, once you create your own constructor, Java no longer automatically provides that no-argument constructor.

For example:

class Student {

    Student(String name) {
        System.out.println(name);
    }
}

Now this will not work:

Student student = new Student();

because the class has a constructor that expects a String.

We would need to provide the argument:

Student student = new Student("John");

Multiple Constructors

A class can have more than one constructor. This is called constructor overloading.

For example:

class Student {
    String name;
    int age;

    Student() {
        name = "Unknown";
        age = 0;
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Now we can create objects in two different ways:

Student student1 = new Student();
Student student2 = new Student("John", 20);

The first object uses the no-argument constructor, while the second uses the constructor that accepts a name and age.

Constructor vs Method

Constructors and methods may look similar, but they have different purposes.

A constructor is mainly used to initialize an object when it is created.

A method is used to perform an action or return a result.

For example:

class Student {

    String name;

    Student(String name) {
        this.name = name;
    }

    void introduce() {
        System.out.println("Hello, my name is " + name);
    }
}

Here, Student() is the constructor because it initializes the object, while introduce() is a method because it performs an action.

There are a few important differences:

Constructor

Method

Same name as the class

Can have any valid name

Has no return type

Can have a return type

Called automatically when an object is created

Usually called explicitly

Used to initialize objects

Used to perform operations

A Complete Example

Let's put everything together:

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void introduce() {
        System.out.println("My name is " + name);
        System.out.println("I am " + age + " years old.");
    }
}

class Main {
    public static void main(String[] args) {

        Student student = new Student("John", 20);

        student.introduce();
    }
}

Output:

My name is John
I am 20 years old.

Here, the constructor initializes the Student object with John's name and age. Then the introduce() method uses that information.

The main thing to remember is that a constructor is automatically called when an object is created and is mainly used to give that object its initial state.