Constructors in Java

Site Admin · 11 Sep 2026 · 10 views

What Is a Constructor?

A constructor is a special method that runs when an object is created with new. It initialises the new object's fields so it is usable immediately.

  • Its name must match the class name.
  • It has no return type - not even void.

Default Constructor

class Student {
    String name;
    // if you write no constructor, this hidden default exists:
    // Student() { }
}
Student s = new Student(); // uses the default constructor
System.out.println(s.name); // null

Once you declare any constructor, the default one disappears.

Parameterised Constructor

class Student {
    String name;
    int age;

    Student(String n, int a) {
        name = n;
        age = a;
    }
}
Student s = new Student("Meena", 21);

Constructor Overloading

class Student {
    String name;
    int age;

    Student() { this("unknown", 0); }        // calls the 2-arg constructor
    Student(String name) { this(name, 0); }
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

The this(...) call must be the first statement of a constructor and lets one constructor delegate to another.

Copy Constructor

Student(Student other) {
    this(other.name, other.age);
}
Student copy = new Student(s);

Key Points

  • Constructors initialise objects and have no return type.
  • Overload them to support different ways of building an object.
  • this(...) chains one constructor to another.
Share this post:

Comments (0)

Please login or register to comment.