Constructor in Java
In object-oriented programming, a constructor is a special method that is called when an object is created. It is used to initialize the object’s state by setting the initial values of its member variables. In Java, a constructor is a method with the same name as the class and no return type.
The constructor is an essential part of the object’s life cycle. It is called immediately after memory is allocated for the object and before the object can be used. Constructors are used to set the initial values of the object’s member variables and to perform any other initialization tasks that are necessary for the object to function properly.

Types of Constructors in Java
Java supports three types of constructors: default constructors, parameterized constructors, and copy constructors.
- Default Constructors
A default constructor is a constructor that takes no arguments. If a class does not define any constructors, the compiler automatically generates a default constructor that takes no arguments. This constructor initializes all the object’s member variables to their default values.
- Parameterized Constructors
A parameterized constructor is a constructor that takes one or more arguments. It is used to initialize the object’s member variables with the values passed as arguments. Parameterized constructors allow objects to be created with specific initial values.
Here’s an example of a copy constructor:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
In the example above, the Person
class has a parameterized constructor that takes two arguments – a String
and an int
. When an object of the Person
class is created using this constructor, the name
and age
member variables are initialized with the values passed as arguments.
- Copy Constructors
A copy constructor is a constructor that takes an object of the same class as an argument. It is used to create a new object that is a copy of the original object. The copy constructor initializes the new object’s member variables with the same values as the original object.
Here’s an example of a copy constructor:
public class Person {
private String name;
private int age;
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
In the example above, the Person
class has a copy constructor that takes an object of the Person
class as an argument. When an object of the Person
class is created using this constructor, the new object’s name
and age
member variables are initialized with the same values as the original object’s name
and age
member variables.