What is a Constructor?
A Constructor is a special method in Java that is automatically called when an object is created.
It is used to initialize object values.
Key Features of Constructor:
Constructor name must be the same as the class name.
Constructor does not have a return type (not even void).
Constructor is called automatically when an object is created.
Used to initialize object data.
Syntax:
class ClassName {
ClassName() {
// Constructor body
}
}
Example:
public class Student {
Student() {
System.out.println("Constructor Called");
}
public static void main(String[] args) {
Student s1 = new Student();
}
}
Output:
Constructor Called
How it Works?
Student s1 = new Student();
↓
Constructor is called automatically
↓
Output: Constructor Called.
Why Do We Use Constructors?
To initialize object values.
To reduce repetitive code.
To set default values when an object is created.
To make object creation easier.
Types of Constructors:
- Default Constructor:
class Student {
Student() {
System.out.println("Default Constructor");
}
}
- Parameterized Constructor:
class Student {
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name);
}
public static void main(String[] args) {
Student s1 = new Student("Bala");
s1.display();
}
}
Output:
Bala