Constructor in Java
What is a Constructor?
A constructor is a special method in Java that is used to initialize objects.
👉 It is automatically called when an object is created.
Key Features of Constructor
Same name as the class
No return type (not even void)
Called automatically when object is created
Used to initialize instance variables
Syntax
class ClassName {
ClassName() {
// constructor body
}
}
Example
class Student {
String name;
Student() {
name = "Abhishek";
}
void display() {
[Link](name);
}
public static void main(String[] args) {
Student obj = new Student(); // constructor called
[Link]();
}
}
Types of Constructors
1️⃣Default Constructor
Provided by Java compiler if no constructor is defined
Initializes variables with default values
class Test {
int x;
public static void main(String[] args) {
Test obj = new Test();
[Link](obj.x); // Output: 0
}
}
2️⃣No-Argument Constructor
Created by programmer
Does not take any parameters
class Demo {
Demo() {
[Link]("No-arg constructor");
}
}
3️⃣Parameterized Constructor
Takes parameters to initialize variables
class Student {
String name;
Student(String n) {
name = n;
}
}
4️⃣Copy Constructor (User-defined)
Copies values from one object to another
class Student {
String name;
Student(String n) {
name = n;
}
Student(Student s) {
name = [Link];
}
}
Constructor vs Method
Feature Constructor Method
Name Same as Any valid name
class
Return No return Must have return
Type type type
Invocatio Automatic Called manually
n
Purpose Initialize Perform
object operations
Important Points
Constructor cannot be static, abstract, or final
Can be overloaded
If no constructor is defined → Java provides default constructor
Used with new keyword
Constructor Overloading
Multiple constructors with different parameters
class Demo {
Demo() {
[Link]("Default");
}
Demo(int x) {
[Link]("Parameterized: " + x);
}
}
this Keyword in Constructor
Used to refer current object
class Student {
String name;
Student(String name) {
[Link] = name; // differentiate variable
}
}
Constructor Chaining
Calling one constructor from another using this()
class Demo {
Demo() {
this(10);
[Link]("Default");
}
Demo(int x) {
[Link]("Parameterized");
}
}
🔻 Short Summary (Exam Ready)
Constructor initializes object
Same name as class, no return type
Types: Default, No-arg, Parameterized, Copy
Supports overloading
Called automatically using new