Constructors in Java - Types of Constructors [With Examples]

A constructor in Java is a special block of code, similar to a method, that is automatically called when an object of a class is created. It's used to initialize the object's fields.

Rules for Writing a Constructor

  • The constructor name must exactly match the class name
  • A constructor has no return type, not even void
  • A constructor is invoked automatically using the new keyword

Types of Constructors

1. Default Constructor

If you don't define any constructor, Java automatically provides a default, no-argument constructor that initializes fields with default values.

class Student {
    String name;
    int age;
    // Java provides: Student() { }
}

2. No-Argument Constructor

A constructor you write yourself that takes no parameters but contains custom initialization code.

class Student {
    String name;
    Student() {
        name = "Unknown";
    }
}

3. Parameterized Constructor

A constructor that accepts arguments to initialize fields with specific values at creation time.

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

Why Constructors Matter

  • They guarantee an object starts in a valid, properly initialized state
  • They remove the need to call a separate "init" method after creating an object
  • They support overloading, letting objects be created in multiple ways
Unlike methods, constructors are never inherited by subclasses, though a subclass constructor can call a superclass constructor using super().

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course