Purpose of Constructors
A Constructor is a special block of code that is called automatically when an object of a class is created. Its primary job is to initialize the object’s attributes (give them starting values).
Think of it this way: When a new student is admitted to a university, they don’t just exist as a “blank” entity. They are immediately given a Name, a Roll Number, and a Department. The “Admission Process” is the Constructor.
Key Characteristics:
It has the exact same name as the Class.
It does not have a return type (not even
void).It is called only once—at the moment of creation using the
newkeyword.
2. The Default Constructor
What happens if you create a class but don’t write any constructor yourself? Java doesn’t leave you hanging.
The Default Constructor is a constructor that is automatically provided by the Java Compiler if (and only if) you do not define any constructor in your class.
It has no parameters (it’s empty).
It initializes numeric variables to
0, booleans tofalse, and objects (like Strings) tonull.
Example of Default Constructor in Action:
class Student {
String name;
int age;
// No constructor written here!
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Java calls the hidden Default Constructor
System.out.println(s1.name); // Output: null
System.out.println(s1.age); // Output: 0
}
}
3. Why do we need Constructors?
In professional programming and university assignments, we want our objects to be “ready to use” as soon as they are born.
Instead of writing:
Student s1 = new Student();
s1.name = "Ali";
s1.age = 20;
We use constructors to do it in one line. It makes the code cleaner, safer, and prevents “empty” or “useless” objects from being created.
4. OOP Comparison: Constructor vs. Method
This is a very common Viva/Exam question for students.
| Feature | Constructor | Method |
| Purpose | To initialize an object. | To perform a specific task/logic. |
| Name | Must match the Class name. | Can be any name (e.g., calculateData). |
| Return Type | None (not even void). | Must have a return type (e.g., int, void). |
| Invocation | Called automatically by new. | Called manually using the dot operator. |
5. Summary for Students
If you don’t write a constructor, Java provides a Default one.
As soon as you write your own constructor (which we will learn in Lesson 2), the default one disappears.
The constructor ensures that your object starts its life with valid data.