A constructor is a specialized member block designed to initialize the state of a newly created object. It is automatically triggered whenever the new operator allocates memory on the Heap.
void. If you specify void MyClass(), the compiler treats it as a standard method, not a constructor!new or via constructor chaining (this(), super()).If a class defines zero constructors, the compiler automatically generates an invisible default constructor:
public class Student {
int rollNumber;
String name;
// Explicit No-Argument Constructor
public Student() {
this.rollNumber = 100;
this.name = "Unknown";
System.out.println("Default constructor initialized!");
}
}
Allows creating objects with customized initial state at the moment of creation:
public class Student {
int rollNumber;
String name;
double gpa;
// Constructor 1: Default
public Student() {
this(0, "Unassigned", 0.0); // Chaining to Constructor 3!
}
// Constructor 2: Two parameters
public Student(int rollNumber, String name) {
this(rollNumber, name, 0.0); // Chaining to Constructor 3!
}
// Constructor 3: Three parameters (Master Constructor)
public Student(int rollNumber, String name, double gpa) {
this.rollNumber = rollNumber;
this.name = name;
this.gpa = gpa;
}
}
this()Constructor Chaining prevents duplicate initialization code by allowing one constructor to delegate to another overloaded constructor in the same class using this(...):
The call to this(...) or super(...) must be the absolute first executable line in a constructor body. Attempting to place code before this() will cause a compilation error: call to this must be first statement in constructor.
Exam Question: "What happens if a developer creates a parameterized constructor, and then writes Student s = new Student();?"
Answer: Compile-time error! As soon as a developer defines any custom constructor with parameters, the compiler withdraws the automatic default constructor. If the developer still needs a no-argument constructor, they must explicitly write an empty public Student() {}.
Now let us examine the multifaceted roles of the this keyword in Java. Proceed to: Java 'this' Keyword →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Understanding this() and references.
Calling parent constructors.
Heap instantiation.
Compact canonical constructors.