Unit 3 · Classes and Objects · 9 min
Constructors
A constructor is a special method that runs automatically when an object is created, used to give the object its starting values.
Why this matters
Without constructors you have to set every field by hand after creating an object, which is long and easy to forget.
Real-life analogy
A constructor is the hospital form filled in the moment a baby is born: name and date are recorded right at creation time.
Syntax
Syntax
class ClassName {
ClassName() { } // default / no-arg constructor
ClassName(int x) { } // parameterised constructor
}Example
Java
class Student {
String name;
int rollNumber;
Student() { // no-argument constructor
name = "Unknown";
rollNumber = 0;
}
Student(String n, int r) { // parameterised constructor
name = n;
rollNumber = r;
}
void display() {
System.out.println(rollNumber + " - " + name);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student();
Student b = new Student("Ananya Rao", 12);
a.display();
b.display();
}
}Output
0 - Unknown 12 - Ananya Rao
Step by step
- 1A constructor has the same name as the class and no return type, not even void.
- 2`new Student()` calls the no-argument constructor.
- 3`new Student("Ananya Rao", 12)` calls the two-argument version — this is constructor overloading.
- 4If you write no constructor at all, Java supplies a hidden default one.
- 5The moment you write any constructor, the hidden default disappears.
Key points
- Same name as class, no return type
- Called automatically by new
- Can be overloaded with different parameter lists
- Writing a parameterised constructor removes the free default one
Common mistakes
- Adding `void` before the constructor name — it becomes an ordinary method
- Calling new ClassName() after defining only a parameterised constructor
- Misspelling the constructor name (case matters)
Try it yourself
- Give the Book class a constructor taking title, author and price.
- Add both a no-arg and a parameterised constructor to a Rectangle class.