Constructor in Java: Types, Rules, and Examples
Constructor in Java
A constructor in Java is a special type of method that is used to initialize the instance variables of a class.
It is automatically called when an object is created.
Unlike normal methods, constructors are mainly used to set initial values for an object.
Rules of Constructor
A constructor must follow these rules:
- The constructor name must be the same as the class name
- A constructor does not have any explicit return type (not even void)
- It is called automatically during object creation
- It is used to initialize instance-level data
Types of Constructors in Java
Constructors are classified into three types:
- Default Constructor
- Zero Parameter Constructor
- Parameterized Constructor
1. Default Constructor
✅ Definition
A default constructor is a constructor that is implicitly created by the Java compiler if no constructor is defined by the programmer.
- It has the same name as the class
- It has no parameters
- Its body contains a super() statement
- It supports object creation
- It does not support static or dynamic initialization
🌍 Real-Life Example
Blank Registration Form
A form is created without any pre-filled data
🧠 Example Code
class Student {
int id;
String name;
}
public class Main {
public static void main(String[] args) {
Student s = new Student(); // default constructor
System.out.println(s.id); // 0
System.out.println(s.name); // null
}
}
2. Zero Parameter Constructor
✅ Definition
A zero parameter constructor is explicitly created by the programmer with:
Same name as class
Zero parameters
It allows:
Object creation
Static initialization
But it does not support dynamic initialization
🌍 Real-Life Example
Employee ID Generation
Default company values are assigned to every employee
🧠 Example Code
class Employee {
int empId;
String company;
Employee() {
empId = 1001;
company = "ABC Corp";
}
}
public class Main {
public static void main(String[] args) {
Employee e = new Employee();
System.out.println(e.empId);
System.out.println(e.company);
}
}
3. Parameterized Constructor
✅ Definition
A parameterized constructor is a constructor created by the programmer that accepts parameters.
It supports:
Object creation
Static initialization
Dynamic initialization
🌍 Real-Life Example
Student Admission System
Each student has different name and roll number
🧠 Example Code
class Student {
int rollNo;
String name;
Student(int r, String n) {
rollNo = r;
name = n;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Rahul");
Student s2 = new Student(102, "Amit");
System.out.println(s1.rollNo + " " + s1.name);
System.out.println(s2.rollNo + " " + s2.name);
}
}
Comments
Post a Comment