Constructor in Java
A constructor is a special member of a class that is used to initialize an object. It is automatically called when an object is created.
A constructor has the same name as the class and does not have a return type, not even void.
Syntax
class ClassName { ClassName() { // initialization } }
Example
class Student { String name; int age; Student() { name = "Anuradha"; age = 22; } void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); } public static void main(String[] args) { Student s = new Student(); s.display(); } }
Output
Name: Anuradha Age: 22
Here, Student() is the constructor. It is automatically called when new Student() creates the object.
Types of Constructors
Java mainly has two commonly discussed types of constructors:
1. Default Constructor
A default constructor is a constructor provided by the Java compiler when no constructor is explicitly defined in the class.
Example:
class Student { String name; } class Main { public static void main(String[] args) { Student s = new Student(); System.out.println(s.name); } }
The compiler provides a default constructor automatically.
2. Parameterized Constructor
A parameterized constructor accepts parameters to initialize an object with specific values.
class Student { String name; int age; Student(String n, int a) { name = n; age = a; } void display() { System.out.println(name + " " + age); } public static void main(String[] args) { Student s1 = new Student("Anuradha", 22); Student s2 = new Student("Ram", 21); s1.display(); s2.display(); } }
Output
Anuradha 22 Ram 21
Constructor Overloading
A class can have multiple constructors with different parameter lists. This is called constructor overloading.
class Student { String name; int age; Student() { name = "Unknown"; age = 0; } Student(String name, int age) { this.name = name; this.age = age; } }
Important Features
- Constructor has the same name as the class.
- It has no return type.
- It is automatically called when an object is created.
- It is mainly used to initialize objects.
- Constructors can be overloaded.
- Constructors are not inherited by child classes.
- A constructor can have parameters.
Constructor vs Method
| Constructor | Method |
|---|---|
| Initializes an object. | Performs a specific operation. |
| Same name as the class. | Can have any valid name. |
| Has no return type. | Can have a return type. |
| Called automatically when an object is created. | Usually called explicitly. |
| Cannot be inherited. | Methods can be inherited. |
Conclusion
A constructor is an important feature of Java OOP. It helps initialize objects when they are created and makes it easier to assign initial values to object properties.