Skip to content

What are Constructors?

A constructor is a special method that is automatically called whenever an object is created.

Its main purpose is to initialize an object’s attributes with starting values.

Why do we need constructors?

Suppose we have a Student class with two attributes:

class Student {
String name;
int age;
}

Without a constructor, we have to create an object first and then assign values one by one.

Student student = new Student();
student.name = "Alice";
student.age = 20;

This works, but it becomes repetitive when creating many objects.

Constructors allow us to provide the values immediately when the object is created!

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

A constructor has the same name as the class and does not have a return type.

Tech tip: Careful on this. You may easily confuse it for a method on a UML diagram

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

Notice that:

  • The constructor is named Student.
  • It has no return type, not even void.
  • It receives values through parameters.
  • It initializes the object’s attributes.

In UML:

UML Example 2

Java Equivalent:

class Student {
private String name;
private int age;
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void introduce() {
System.out.println("Hi! My name is " + name + " and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20);
student.introduce();
}
}
  • A constructor is automatically called when an object is created.
  • Its purpose is to initialize an object’s attributes.
  • A constructor has the same name as its class.
  • Constructors do not have a return type.
  • The this keyword refers to the current object.
  • If no constructor is written, Java provides a default constructor automatically.
  • Once you create your own constructor, the default constructor is no longer generated.