Java Constructors

Learn how objects are initialized in Java

1. What is a Constructor?

A constructor is a special block of code used to initialize objects when they are created. It is called automatically when an object of a class is instantiated using the new keyword[

Key Rules for Constructors:
  • Must have the exact same name as the class
  • Must NOT have a return type not even void
  • Cannot be abstract, static, or final
new Student() Object Creation Triggers Student() Constructor Initializes Instance State

2. Default vs. No-Arg Constructor

If you don't write any constructor in your class, Java automatically provides a Default Constructor that sets variables to default values (e.g., 0, null, false)

class Student {
    String name;
    int rollNo;

    // Default Constructor is added behind the scenes by Java Compiler!
    // Student() { }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student(); // Calls default constructor
        System.out.println(s.name);   // Output: null
        System.out.println(s.rollNo); // Output: 0
    }
}

3. Parameterized Constructor

A constructor that accepts parameters is used to initialize object attributes with specific custom values upon creation

"Anu", 101 Arguments Student(String n, int r) this.name = "Anu" this.rollNo = 101
class Student {
    String name;
    int rollNo;

    // Parameterized Constructor
    Student(String n, int r) {
        name = n;
        rollNo = r;
    }
}

public class Main {
    public static void main(String[] args) {
        // Passing arguments directly during instantiation
        Student s1 = new Student("Anu", 101);
        System.out.println(s1.name + " - " + s1.rollNo); // Output: Anu - 101
    }
}

4. Constructor Overloading

Having multiple constructors in the same class, each with a different parameter list (number or types of arguments)[cite: 2].

Student Class Student() [No-arg] Student(name, rollNo)
class Student {
    String name;
    int rollNo;

    // Constructor 1: Default values
    Student() {
        name = "Unknown";
        rollNo = 0;
    }

    // Constructor 2: Parameterized
    Student(String name, int rollNo) {
        name = name;
        rollNo = rollNo;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();             // Calls Constructor 1
        Student s2 = new Student("Rahul", 102); // Calls Constructor 2
    }
}